Angular,从动态创建的Component获取ViewChild / ViewContainerRef

时间:2017-05-26 08:22:06

标签: angular viewchild

有没有办法从动态创建的组件中获取ViewContainerRef? 我的动态创建组件里面有一个ngContent元素,我想在动态创建后填充它。

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

}

我想一些解决ViewChild而不是使用装饰器的手动方法。一些想法?

非常感谢。

2 个答案:

答案 0 :(得分:0)

我不确定如何动态添加viewchild。但是,如果动态ViewContainerRef是您想要的,您可以尝试使用此解决方案:

在html文件中创建:

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

在您的组件中创建:

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

答案 1 :(得分:0)

如果您阅读了这两篇文章,可以回答您的问题,它为我解决了这个问题:

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

第二篇文章在Github上包含工作角度示例,您可以通过4种不同的方式查看动态创建的组件的工作示例。

相关问题