如何从ViewContainerRef-Angular 9获取子组件?

问题描述

我在viewContainerRef内部添加了动态组件(ChildComponent.ts)。我可以像这样从viewContainerRef.length从viewContainerRef获取子计数,如果我使用索引来获取子组分(viewContainerRef.get(0)),则返回ViewRef,但是我需要子组分该怎么做。

示例:

@ViewChild("cards_holder",{ read: ViewContainerRef }) cards_holder: ViewContainerRef;

 const componentFactory = this.resolver.resolveComponentFactory( SimpleCardComponent);
const componentRef = this.cards_holder.createComponent(componentFactory);

for (let index = 0; index < this.cards_holder.length; index++) {
    console.log(this.cards_holder.get(index)) //It's Return ViewRef but i need SimpleCardComponent
}

谢谢。 Sabish.M

解决方法

createComponent返回组件引用以来,您可以像这样访问SimpleCardComponent实例:

money.instance.setMoney(-turretBuildCost);