【问题标题】:Angular, get ViewChild / ViewContainerRef from dynamic created ComponentAngular,从动态创建的组件中获取 ViewChild / ViewContainerRef
【发布时间】:2017-10-27 01:40:55
【问题描述】:

有没有办法从动态创建的组件中获取 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 而不是使用装饰器。一些想法?

非常感谢。

【问题讨论】:

    标签: angular viewchild


    【解决方案1】:

    我也不确定如何动态添加 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);
    

    【讨论】:

      【解决方案2】:

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

      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 上的工作 Angular 示例,您可以在其中以 4 种不同方式查看动态创建的组件的工作示例。

      【讨论】:

        猜你喜欢
        • 2018-12-01
        • 2020-03-22
        • 2020-01-03
        • 2017-03-13
        • 2020-12-08
        • 2020-07-18
        • 2022-12-15
        • 2023-03-09
        • 2016-12-26
        相关资源
        最近更新 更多