使用`ViewChild` - 方法不会调用子方法

时间:2018-05-10 06:34:15

标签: angular

我正在尝试从父级调用我的子组件方法,但根本不起作用。

这是我的代码:

<router-outlet>
   <app-modal-popup></app-modal-popup> //children for all pages!!
</router-outlet>

在主页:

    import { Component, OnInit, Output, ViewChild, AfterViewInit  } from '@angular/core';
    import { ModalPopupComponent } from '../../shared/modal/modal-popup/modal-popup.component';

    export class HomeComponent implements OnInit, AfterViewInit {

        @ViewChild('appModal') private appModal : ModalPopupComponent;

    footerLinkHandler(link){
        console.log('link', link );
        this.appModal.popMessage(link);
        return false;
    }

}

但是收到错误Cannot read property 'popMessage' of undefined - 问题是什么。但是我从popMessage获取appModal为自动填充。

1 个答案:

答案 0 :(得分:0)

试试这个

@Component({
 ...
directives: [ModalPopupComponent]
})

class HomeComponent implements OnInit, AfterViewInit{
 @ViewChild(ModalPopupComponent) childComp:ModalPopupComponent;
 ...
 footerLinkHandler(link){
    console.log('link', link );
    this.childComp.popMessage(link);
    return false;
 }