Angular, get ViewChild / ViewContainerRef from dynamic created Component

♀尐吖头ヾ 提交于 2020-01-03 10:23:09

问题


is there a way to get the ViewContainerRef from a dynamic created component? My dynamic created component has an ngContent element inside, which i want to fill after the 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 think about some manual way to resolve the ViewChild instead of using the decorators. Some Ideas?

Thanks a lot.


回答1:


I am not sure as well how to add viewchild dynamically. however, if dynamic ViewContainerRef is what you want, you can try using this solution:

in the html file create:

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

in your component create:

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



回答2:


Your question can be answered if you read those two articles, it solved it for me:

https://blog.angularindepth.com/here-is-how-to-get-viewcontainerref-before-viewchild-query-is-evaluated-f649e51315fb

https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e

The second article contains working angular examples on Github where you can check out working examples of dynamically created Components in 4 different ways.



来源:https://stackoverflow.com/questions/44196872/angular-get-viewchild-viewcontainerref-from-dynamic-created-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!