Home > Blockchain >  property not updating passed to modal componentProps
property not updating passed to modal componentProps

Time:10-02

I am using modal in Ionic and I am passing componentProps:

    //in the Main component
    someList:number[] = [1, 2];
    someString:string = "test";

    async presentModal(ev: any) {
           const modal = await this.modalController.create({
           component: ModalComponent,
           componentProps: {
                  someList: this.someList,
                  someString: this.someString
             }
          });
         await modal.present(); 
     }

The modal component ModalComponent itself defines

    @Input('someList') someList;
    @Input('someString') someString;

When I update in the ModalComponent:

    this.someList.push(3);

...it reflects the change in the the Main component/template. but if I update

   this.someString = "new string";

...it does not reflect in the main component/template.

Not exactly sure why, any way around this?

NOTE: I can get around this by passing "this" to componentProps:

      componentProps: {
              ref: this
      }

...and then accessing the "someString" property from "ref" (ie: ref.someString), and it will reflect in the Main component/template when changed in the ModalComponent. But I feel that passing a reference to the entire component is not good practice.

CodePudding user response:

You can pass back the changes to your main component after the modal dismiss like this:

dismiss() {
    this.modalController.dismiss({
      someString: this.someString,
    });
}

and in your parent component add this after the init of the modal:

modal.onDidDismiss().then(data => {
  this.someString= data.data.someString;
});

so it will look for you like this:

    async presentModal(ev: any) {
           const modal = await this.modalController.create({
           component: ModalComponent,
           componentProps: {
                  someList: this.someList,
                  someString: this.someString
             }
          });
         modal.onDidDismiss().then(data => {
           this.someString= data.data.someString;
         });
         await modal.present(); 
     }
  • Related