简体   繁体   English

Angular:如何从父级访问子级。 ViewChild、ContentChild 都不能在特定场景下工作

[英]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 参考代码

This might help someone who has faced similar issue.这可能会帮助遇到类似问题的人。 As, it is standalone components.因为,它是独立的组件。 I tried to import the child component inside the parent component and it worked as expected.我尝试将子组件导入到父组件中,它按预期工作。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM