首页 > 解决方案 > Angular 9:如何从 templateRef 访问子组件实例

问题描述

在 Angular 8 中,我能够从 templateRef 访问子组件,如下所示:

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

但是在将应用程序迁移到版本 9 之后,一切都发生了变化。现在,我在模板中没有投影视图。

现在我将以下属性视为 templateRef 的一部分

templateRef
 -> elementRef
 -> _declarationContainer
 -> _declarationView

我现在如何访问 Angular 9 中的子组件实例?

标签: angularangular9

解决方案


要访问您的子组件,请尝试如下:

  @ViewChild(ChildComponent) template: ChildComponent;

ChildComponent您的子组件的类名在哪里。

现在template您将能够访问子组件的属性。


推荐阅读