首页 文章

Angular 2 ionic 2,调用子组件undefined

提问于
浏览
0

我的离子应用程序中有一个全局页脚,就像我这样做的方式 . 我在离子导航器中添加了选择器组件,它运行良好 . 我的页脚显示在每个页面中 .

app.html

<ion-nav [root]="rootPage" #content swipeBackEnabled="false">

</ion-nav>
<call-footer #CallChild></call-footer>

但是,在一个页面中,我想控制页脚,我可能会隐藏它或更改其中的变量 . 在我的页脚组件中,我有一个名为'test'的函数,在其中一个页面('calls')中,我正在尝试这个 .

calls.ts

import { Component, OnInit, ViewChild} from '@angular/core';

import { oncallpage } from '../calls/oncall/oncall';
import { callfooter } from '../../components/callfooter/callfooter.component';

@Component({
    selector: 'page-calls',
    templateUrl: 'calls.html'
})
export class callspage implements OnInit {

    @ViewChild('CallChild') child;


    constructor() { }


      ngAfterViewInit() {
         this.child.test(); //error
  }

但是我得到 "Cannot read property 'test' of undefined"

我不确定是否存在语法错误或者我错过了一些想法 . 我该如何解决这个案子?

1 回答

  • 4

    @ViewChild 返回 ElementRef . 你不能调用这样的函数 .

    解决方法是使用ionic的 Events (docs)

    将您的功能更改为:

    ngAfterViewInit() {
       this.events.publish("child:test");
    }
    

    在您的子页面中:

    constructor(events: Events) {
      events.subscribe("child:test", ()=> {
         this.test();
      });
    }
    
    test() { console.log("test called"); }
    

    另外,有关更详细的说明,请参阅我的答案How to update value inside ionic 2 side menu

相关问题