-1

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

Sabish.M
  • 2,022
  • 16
  • 34

1 Answers1

0

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

const componentRef = this.cards_holder.createComponent(componentFactory);
const compInstance = <SimpleCardComponent>componentRef.instance;
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
  • I hope you are tamil. I am from Tirunelveli. Is possible get ComponentRef from ViewContinerRef after create Componenet. – Sabish.M Aug 19 '20 at 12:08
  • createComponent method available in viewContainerRef class only, But i dont think it's possible to get the component instance from ViewRef – Chellappan வ Aug 19 '20 at 12:20
  • @Sabish.M can't you store them manually? something like: `cards_holder.children = []; cards_holder.children.push(componentRef)`? so you don't loose the reference after creation. – yaya Aug 19 '20 at 12:33
  • I know this. I just asking get componenetRef without store the component reference anywhere . – Sabish.M Aug 19 '20 at 12:52