angularangular-materialmat-dialog

Angular parent mat dialog component is changed from a child mat dialog component


I am openening a mat dialog for creating some object. In this mat dialog i can preview some data by clicking "preview" button, and then opens child mat dialog from my parent dialog, where i passing an object for a preview. The problem is that this object contains base64 format of a photo and in the opened mat dialog i am changing photo to the next format: data:image/png;base64,${base64_photo}. But for some reason it also changes in the main mat dialog, and when i an trying to open preview of the same object oen more time, the photo won't be as base64 but it will be of the next format: data:image/png;base64,${base64_photo}. And how many times I open the preview of the same object, so many times data:image/png;base64, will be added. I tried to pass something like {...this.scenario[i]} or Object.assign({}, this.scenario[i]) but it is still changing. Downbelow you can see the code.

Here i am opening the dialog with the specific scenario:

openPreviewModel(i: number) {
  this.matDialog.open(PreviewScenariosComponent, {data: this.scenarios[i]});
}

This is my second mat dialog where i am changing the photo:

constructor(private matDialogRef: MatDialogRef<PreviewScenariosComponent>,
    private _client: BackendService, @Inject(MAT_DIALOG_DATA) public data: any) {
}

ngOnInit(): void {
  // console.log(this.data)
  this.scenario = this.data as ScenarioPreview;
  for (let j = 0; j < this.scenario.photos.length; j++) {
    let base64_photo = this.scenario.photos[j]
    this.scenario.photos[j] = `data:image/png;base64,${base64_photo}`
  }
  this.current_photo = this.scenario.photos[this.current_photo_index];
}

This is my ScenarioPreview model if needed:

export class ScenarioPreview {
  id: number = 0;
  name: string = "";
  description: string = "";
  languages: string[] = [];
  photos: string[] = [];

  public constructor(init?: Partial<ScenarioPreview>) {
    Object.assign(this, init);
  }
}

I am expecting to understand where i made a mistake.

P.S. I think i can in the main dialog when i am reading all scenarios just add this strings and don't do it in the child dialog and the problem shuld go away, but i am intersted what i did wrong.


Solution

  • I just used JSON.parse(JSON.stringify(object))

    Mat dialog, when passing an object from the parent to the child mat dialog, it changed it both in the child and in the parent. Accordingly, in order to avoid this, it was necessary to use copying the object instead of transferring it itself. Object.assign({}, this.scenario[i]) didn't help. But in turn with JSON.parse(JSON.stringify(this.scenarios[i])) everything works. Rather, the error lies in the fact that Object.assign() did not copy arrays, thereby passing a reference to the parent object