Ionic 2: Как вызвать функцию родительской страницы из компонента Popover

У меня есть компонент страницы с кнопкой, которая открывает PopoverController. Согласно Ionic Docs, поповерам нужен еще один специфический компонент для их контента.

На главной странице у меня есть функция, которую мне нужно вызывать из компонента 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, поэтому любая помощь будет очень благодарна!

2 ответа

Решение

Вы можете передавать данные (и функции) в поповер, передавая объект в качестве второго аргумента 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();
    }

}
Другие вопросы по тегам