3

我有一个带有打开 PopoverController 的按钮的页面组件。根据 Ionic Docs,popovers 的内容需要另一个特定的组件。

在主页中,我有一个需要从 popover 组件调用的函数,但我还没有找到如何访问“父母”方法。我试过了,@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,因此非常感谢您的帮助!

4

3 回答 3

12

您可以通过将对象作为第二个参数传递给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')(); 
    }
}
于 2017-01-30T20:36:18.713 回答
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();
}
于 2018-09-22T13:44:43.420 回答
0

父页面:

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

}
于 2020-03-23T00:01:53.300 回答