我有一个页面组件,上面有一个按钮可以打开一个PopoverController。根据Ionic Docs的说法,弹出框的内容需要另一个特定的组件。
在主页中,我有一个需要从弹出组件调用的函数,但我还没有找到如何访问"父母"的方法。我试过@ViewChild
但孩子undefined
了。
import { Component, ViewChild } from '@angular/core';
import { Content, NavController, NavParams, Platform, PopoverController, ViewController } from 'ionic-angular';
// Parent page:
@Component({
selector: 'page-favorites',
templateUrl: 'favorites.html'
})
export class FavoritesPage {
constructor(public popoverCtrl: PopoverController) {
}
openOptions(ev?: Event) {
let popover = this.popoverCtrl.create(FavoritesPopover);
popover.present({ ev: ev });
}
showConfirm() {
// This is the function I need to call from FavoritesPopover
}
}
// Popover content:
@Component({
template: `
<ion-list>
<button ion-item (click)="showConfirm()">Show confirm</button>
</ion-list>`
})
export class FavoritesPopover {
@ViewChild(FavoritesPage) favoritesPage: FavoritesPage;
showConfirm() {
this.favoritesPage.showConfirm(); // It doesn't work, favoritesPage is undefined
}
}
如您所见,我刚刚开始使用 Ionic 2 和 Angular,所以任何帮助都将不胜感激!
通过将对象作为第二个参数传递给 create
方法,可以将数据(和函数)传递给弹出框:
openOptions(ev?: Event) {
let popover = this.popoverCtrl.create(FavoritesPopover, {
showConfirm: function() {
alert('yay');
}
});
popover.present({ ev: ev });
}
然后,您应该将NavParams
注入到弹出框视图中,并get
您传递的函数:
import {NavParams} from 'ionic-angular';
export class FavoritesPopover {
constructor(public params: NavParams) {}
showConfirm() {
this.params.get('showConfirm')();
}
}
对于遇到相同问题的人,最简单的方法是按如下方式传递页面的引用:
let popover = this.popCtrl.create(PopoverPage, { homeRef: this });
popover.present({
ev: myEvent
});
在弹出窗口页面中,您可以获取引用并访问该页面的所有变量和函数,如下所示:
homePage: any;
changePassword() {
this.homePage = this.navParams.get('homeRef');
this.homePage.changePassword();
this.viewCtrl.dismiss();
}
父页面:
public list() {
this.popover.dismiss();
}
public async more(ev:any) {
this.popover = await this.pop.create({
component: PopoverPage,
componentProps: {ref: this},
});
return await this.popover.present();
}
弹出框页面:
export class PopoverPage {
parentPage: any;
constructor(
public params: NavParams
) {
}
order() {
this.parentPage = this.params.get('ref');
this.parentPage.list();
}
}