首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将动态组件添加到ViewChildren

将动态组件添加到ViewChildren
EN

Stack Overflow用户
提问于 2019-02-18 16:50:55
回答 1查看 3.3K关注 0票数 5

目前,我可以动态加载单个组件并将其显示在ViewChild中,如下所示:

代码语言:javascript
复制
@Component({
   selector: '...',
   template: '<ng-container #viewRef></ng-container>'
})
export class SomeComponent {
@ViewChild('viewRef', {read: ViewContainerRef}) public viewRef;

  constructor(private compiler: Compiler) {}

  ngAfterViewInit() {
    this.compiler.compileModuleAndAllComponentsAsync(SomeModule).then((factory) =>  {
      this.componentRef = this.placeholder.createComponent(factory);
    });
  }
}

现在我想加载多个组件,并在列表中动态显示它们。ViewChildren应该是这个问题的解决方案。问题是,ViewChildren不允许添加新元素或创建类似于ViewChild上的createComponent的元素。

如何创建动态组件并将其添加到ViewChildren

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-18 19:44:42

您可以使用ViewChildren从视图DOM中获取元素或指令的QueryList。任何时候添加、删除或移动子元素时,查询列表都将更新,并且查询列表的可观察到的更改将发出新值。这意味着您可以在viewRefs.changes事件上创建订阅,并使用ComponentFactoryResolver动态加载组件。如下例所示:

代码语言:javascript
复制
export class SomeComponent {
    @ViewChildren('viewRef', {read: ViewContainerRef})
    public viewRefs: QueryList<ViewContainerRef>;

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {
    }

    ngAfterViewInit() {
        this.viewRefs.changes.subscribe((list: QueryList<ViewContainerRef>) => {
            list.forEach((viewRef: ViewContainerRef, index: number) => {
                const componentFactory: ComponentFactory<any> = this.componentFactoryResolver.resolveComponentFactory(OtherComponent);
                viewRef.createComponent(componentFactory, index);
            });
        });
    }
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54743427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档