我有一个页面组件,其中包含一个打开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,所以任何帮助都会非常感谢!
答案 0 :(得分:10)
您可以通过将对象作为第二个参数传递给create
方法,将数据(和函数)传递给popover:
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')();
}
}
答案 1 :(得分:2)
对于遇到同样问题的人们,最简单的方法是按照以下方式传递页面的引用:
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();
}
答案 2 :(得分:0)
父页面:
string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy","dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy"};
if (DateTime.TryParseExact(date, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime DOB))
{
// DOB variable is ready to use
Label1.Text = DOB.ToShortDateString();
} else {
//error handling goes here
Label1.Text = "ERROR: Invalid value";
}
弹出页面:
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();
}