简体   繁体   中英

How to get Child Components from ViewContainerRef - Angular 9?

I added dynamic components ( ChildComponent.ts ) inside viewContainerRef. I able to get child count from viewContainerRef like this viewContainerRef.length if i use index to get Child Component ( viewContainerRef.get(0) ) it's return ViewRef But i need child component how to do this.

Example:

@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
}

Thank you. Sabish.M

Since createComponent return component refernce you can access SimpleCardComponent instance like this:

const componentRef = this.cards_holder.createComponent(componentFactory);
const compInstance = <SimpleCardComponent>componentRef.instance;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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