首页 > 解决方案 > 使用 `ViewChild` - 方法没有调用子方法

问题描述

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

这是我的代码:

<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- 有什么问题。但我得到的popMessageappModal自动填充的。

标签: angular

解决方案


尝试这个

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

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

推荐阅读