首页 > 解决方案 > 属性未更新传递给模态 componentProps

问题描述

我在 Ionic 中使用模态,并且正在传递 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(); 
         }

模态组件 ModalComponent 本身定义

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

当我在 ModalComponent 中更新时:

        this.someList.push(3);

...它反映了主要组件/模板的变化。但如果我更新

       this.someString = "new string";

...它没有反映在主要组件/模板中。

不完全确定为什么,有什么办法吗?

注意:我可以通过将“this”传递给 componentProps 来解决这个问题:

          componentProps: {
                  ref: this
          }

...然后从“ref”访问“someString”属性(即:ref.someString),当在 ModalComponent 中更改时,它将反映在 Main 组件/模板中。但我觉得传递对整个组件的引用并不是一个好习惯。

标签: angularionic-framework

解决方案


您可以在模态关闭后将更改传递回主组件,如下所示:

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

并在您的父组件中在模式的初始化之后添加:

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

所以它会像这样寻找你:

    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(); 
     }

推荐阅读