Angular, get ViewChild / ViewContainerRef from a dynamically created component

Is there a way to get ViewContainerRef from a dynamically created component? My dynamically created component has an ngContent element inside, which I want to fill after dynamic creation.

export class Example {

  @ViewChild('content', { read: ViewContainerRef }) //normal way
  content: ViewContainerRef;

...

  ngAfterViewInit(){
    let box1=this.content.createComponent(this.boxFactory);
    box1.instance.title="Dynamic (1)";
    // HERE: the box1 has a ng-content area which i want to fill.
  }

}

I am thinking of some manual way to enable ViewChild instead of using decorators. Some ideas?

Many thanks.

+4
source share
2 answers

I'm also not sure how to dynamically add a viewchild. however, if the dynamic ViewContainerRef is what you want, you can try using this solution:

in the html file create:

  <div id="test"></div>

in your create component:

 let nodeElement = document.getElementById("test");
      let compFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
      let component = compFactory.create(this.viewContainerRef.injector, null, nodeElement);
0
source

Source: https://habr.com/ru/post/1677971/


All Articles