Modal update original data - problem

Hello everybody.
I don’t know what i’m doing wrong with modals. I open a simple modal instance and present it. To this modal i will pass data which is an array of objects as options . In the modal i will run a ngFor to render this data, each object from data is represented by a checkbox. Clicking on a checkbox will add to the object a field checked which will be either true or false.
Now the problem appears when i dismiss the modal. The original data which was passed by the component from where i opened the modal will be updated too with the checked field .
Can somebody tell me what happens ?

Here is an example:

      class MyClass{
        constructor(...)

        openDialog(){
          this.dialog.create(MyModal, { values: this.values }, {});
        }
      }


      class MyModal{
        constructor(...){
           this.values = this.viewCtrl.data.values
        }

        cancel(){
          this.viewCtrl.dismiss();
        }

        done(){
          //do something and dimiss
          this.viewCtrl.dismiss();
        }
      }
  • modal template
<ion-header>
</ion-header>
<ion-content>
  <ion-list>
    <ion-item *ngFor="let value of values">
      <ion-label>
        {{ value.name }}
      </ion-label>
      <ion-checkbox [(ngModel)]="value.checked">
      </ion-checkbox>
    </ion-item>
  </ion-list>
</ion-content>
<ion-footer>
    <button (tap)="done()">Done</button>
    <button (tap)="cancel()">Cancel</button>
</ion-footer>

Please post your ionic info output.

@ionic/cli-plugin-ionic-angular : 1.4.0
@ionic/cli-utils                : 1.6.0
ionic (Ionic CLI)               : 3.6.0

local packages:

@ionic/app-scripts : 2.1.3
Ionic Framework    : ionic-angular 3.6.0

System:

Node : v6.10.3
OS   : Windows 8.1
npm  : 3.10.10

I think the issue is that when you pass an array of objects to the modal, the value you get from navParams inside the modal is a reference to the array and not the array itself. I’m not sure what the recommended way to deal with this is, but this should work:

export class MyModal {
  values = [];

  constructor(public navParams: NavParams,
    public viewCtrl: ViewController) {
    this.values = JSON.parse(JSON.stringify(this.navParams.get('values')));
  }
  
}

2 Likes

it worked thank you very much :slight_smile: !

An alternative is the lodash clone functions.

1 Like