首页 > 解决方案 > 如何根据按钮的点击事件提供此功能的不同道具?

问题描述

我正在尝试重用一个函数来在 Ionic 4 中打开一个模态。这两者虽然是分开的,但更愿意根据它们的独立参数进行组合,以更改出现的模态中的标题。

这不会编译,但显示了我本质上想要实现的目标:

async openModal(edit, add) {
    const modal = await this.modalController.create({
        component: ModalComponent,
        componentProps: {
            if (edit) {
                'title': 'Edit Firehouse'
            else if (add) {
                'title': 'Add Firehouse'
            },
            'firehouseShow': true
        }
    });
    return await modal.present();
}

这是当前的内容,即使出现错误也可以编译:

'重复的功能实现。

async openModal(edit) {
    const modal = await this.modalController.create({
        component: ModalComponent,
        componentProps: {
            'title': 'Edit Firehouse',
            'firehouseShow': true
        }
    });
    return await modal.present();
}

async openModal(add) {
    const modal = await this.modalController.create({
        component: ModalComponent,
        componentProps: {
            'title': 'AddFirehouse',
            'firehouseShow': true
        }
    });
    return await modal.present();
}

这些函数是通过 Angular 按钮单击事件调用的:

<ion-button (click)="openModal(edit)">Edit</ion-button>
<ion-button (click)="openModal(add)">Add</ion-button>

我更愿意重用这个函数,特别是因为它只在一个页面上(一次)被调用。但是,它确实会动态更改模式中显示的内容以及每次点击事件填充或不填充的数据。例如,“添加”点击事件不会检索任何数据,但“编辑”会。

标签: javascriptangulartypescriptionic-frameworkcomponents

解决方案


即使解决了重复功能问题,第二个也无法工作,因为两个功能都做同样的事情。

考虑传递componentPropsas 参数。

async openModal(componentProps) {
    const modal = await this.modalController.create({
        component: ModalComponent,
        componentProps
    });
    return await modal.present();
}

当调用一个函数时:

openModal({
 'title': 'Edit Firehouse',
 'firehouseShow': true
})
// or
openModal({
 'title': 'Add Firehouse',
 'firehouseShow': true
})

更新

如果您只想获取标题作为参数,请在创建对象时设置标题。

async openModal(title) {
    const modal = await this.modalController.create({
        component: ModalComponent,
        componentProps : {
          'title': title,
          'firehouseShow': true
      }
    });
    return await modal.present();
}

接着:

openModal('Edit Firehouse')
// or
openModal('Add Firehouse')

推荐阅读