Angular 9: how do I access child component instance from templateRef

Viewed 570

In angular 8, I was able to access child component from templateRef as below:

<ng-template #templateName>
 <child-component></child-component>
</ng-template>
@ViewChild('templateName') template;
    
const childComponent = template._projectedViews[0].nodes[1].instance;

But after migration application to version 9, everything has change. Now, I do not have projected views in template.

Now I see below attributes as part of templateRef

templateRef
 -> elementRef
 -> _declarationContainer
 -> _declarationView

How do I now access child component instance in angular 9?

1 Answers

To access your child component, try like this:

  @ViewChild(ChildComponent) template: ChildComponent;

where ChildComponent is the class name of your child component.

Now with template you will able to access the child component's properties.

Related