angular - 使用 `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
- 有什么问题。但我得到的popMessage
是appModal
自动填充的。
解决方案
尝试这个
@Component({
...
directives: [ModalPopupComponent]
})
class HomeComponent implements OnInit, AfterViewInit{
@ViewChild(ModalPopupComponent) childComp:ModalPopupComponent;
...
footerLinkHandler(link){
console.log('link', link );
this.childComp.popMessage(link);
return false;
}
推荐阅读
- python-3.x - Pandas - 用于设置值的 reindex 与 loc 的行为/问题
- python - 与包含的相关对象合并时,不会保留新关系
- c++ - 从 C++ 读取 QML 数组属性
- batch-file - 使用 findstr 正则表达式在管道结果中搜索模式
- flutter - 将数据从本机发送到颤振
- r - 如果使用严格的不等式,为什么 ifelse 返回一个 1 的向量?
- timezone - 不能将 filebeat [beat][timezone] 与 logstash 日期过滤器插件一起使用?
- encryption - 现代 64 位处理器通常如何处理 128 位/256 位加密?
- c# - 发布到 web api
- uwp - 应用程序包 (appx) 不会将 WebExtension 安装到 Edge