gpt4 book ai didi

angular - 向 ViewChildren 添加动态组件

转载 作者:行者123 更新时间:2023-12-03 23:13:33 26 4
gpt4 key购买 nike

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

@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不允许添加新元素或创建它们类似于 createComponentViewChild .

如何创建动态组件并将它们添加到 ViewChildren ?

最佳答案

您可以使用 ViewChildren 从 View DOM 中获取元素或指令的 QueryList。每当添加、删除或移动子元素时,查询列表都会更新,查询列表的可观察更改将发出一个新值。这意味着您可以在 viewRefs.changes 上创建订阅。使用 ComponentFactoryResolver 动态地事件和加载组件.请参阅下面的示例:

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);
});
});
}
}

关于angular - 向 ViewChildren 添加动态组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54743427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com