[英]Angular: How to access child from the parent. ViewChild, ContentChild none of them are working in specific scenario
I have parent component with the below code我有以下代码的父组件
<div class="parent">
parent >>>
<p>This my parent having child in it</p>
<div appChildDom >
<ng-content></ng-content>
</div>
</div>
Child component is defined as below,子组件定义如下,
@Component({
selector: "div[appChildDom]",
template: "",
styleUrls: ["./child.component.css"]
})
export class ChildComponent implements OnInit, AfterViewInit {
constructor() {}
ngAfterViewInit(): void {
console.log("init child");
}
ngOnInit() {}
getContentOfChild() {
alert('child');
}
}
In my parent component, im accessing the child using the ViewChild decorator and trying to call the method on the child component.在我的父组件中,我使用 ViewChild 装饰器访问子组件并尝试调用子组件上的方法。
export class ParentComponent implements OnInit {
@ViewChild(ChildComponent) vchild: ChildComponent;
constructor() {}
ngAfterViewInit(): void {
// this.vchild is always undefined
alert(this.vchild);
// I want to access the child component
this.vchild.getContentOfChild();
}
ngOnInit() {}
}
Im able to access the ElementRef but not the childComponent instance.我能够访问 ElementRef 但不能访问 childComponent 实例。 How to achieve this?
如何做到这一点? Is this not correct way of defining the parent and child components?
这不是定义父组件和子组件的正确方法吗? Refer the code here
参考这里的代码
Similar approach works in angular 11.x refer the code类似的方法适用于 angular 11.x 参考代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.