【发布时间】:2021-04-12 16:14:59
【问题描述】:
我正在尝试从我的父组件调用子组件的公共方法,但我收到了错误
core.js:5967 ERROR TypeError: this.foo.bar 不是函数
我理解这是因为即使我的 ViewChild 是 ChildComponent 类型,它实际上不是 ChildComponent,它只是与 ChildComponent 相同的形状,但最终只是一个普通的旧 JS 对象。
那么如何在子组件上调用公共方法呢?
我的代码如下:
父.html
<app-child-component #childComponent></app-child-component>
父.ts
export class ParentComponent implements OnInit {
{
@ViewChild('childComponent') childComponent:ChildComponent;
ngOnInit(): void {
this.childComponent.foo(); // ERROR TypeError: this.childComponent.foo is not a function
}
}
childComponent.ts
export class ChildComponent implements OnInit {
{
public foo(): void
{
// ...
}
}
【问题讨论】:
-
你能检查一下父级中
childComponent的实例是什么吗?通过控制台.log -
试试 AfterViewInit 而不是 OnInit。
-
也可以按班级查询
@ViewChild(ChildComponent) childComponent: ChildComponent;
标签: angular