角动态组件:@ViewChildren为QueryList中的每个组件获取ViewContainerRef [英] Angular Dynamic Components: @ViewChildren get ViewContainerRef for every component in QueryList
问题描述
我正在构建一个带有动态选项卡的对话框,该对话框可以接收要放置在选项卡主体中的组件.我很难使用@ViewChildren创建多个动态组件.过去我很容易用一个组件和@ViewChild来完成此操作.
I am building a dialog with dynamic tabs that can receive a component to be placed in the tab body. I am having a hard time creating multiple dynamic components using @ViewChildren. I have successfully done this with a single component and @ViewChild in the past quite easily.
这是我的模板:
<mat-tab *ngFor="let tab of tabs" [label]="tab.label">
<ng-template #comp></ng-template>
</mat-tab>
这是我的组件逻辑:
@ViewChildren("comp") dynComponents: QueryList<any>;
public ngAfterContentInit() {
this.tabs.forEach(tab => {
const factory = this._resolver.resolveComponentFactory(tab.component);
console.log(this.dynComponents); // Returns undefined.
// this.componentRef = this.vcRef.createComponent(factory);
});
}
即使在模板中对组件进行硬编码时,我的dynComponents也未定义.我似乎需要从此dynComponents QueryList获取ViewContainerRef,但是我不确定为什么它根本没有填充.我将此帖子用作参考:帖子
My dynComponents are undefined even when hard-coding components in the Template. I need to seemingly get the ViewContainerRef from this dynComponents QueryList, but I am not sure why it is not populating at all. I used this post for reference: Post
推荐答案
@ViewChildren
无效,因为它缺少指示ViewContainerRef
的read
元数据属性.
import {
AfterContentInit, Component, ComponentFactoryResolver, QueryList, Type, ViewChildren, ViewContainerRef
} from '@angular/core';
@Component({
selector: 'dynamic-dialog',
templateUrl: './dynamic-dialog.component.html',
styleUrls: ['./dynamic-dialog.component.scss']
})
export class DynamicDialogComponent implements AfterContentInit {
@ViewChildren('comp', { read: ViewContainerRef })
public dynComponents: QueryList<ViewContainerRef>;
public tabs = [];
constructor(private _resolver: ComponentFactoryResolver) {}
ngAfterContentInit() {
this.dynComponents.map(
(vcr: ViewContainerRef, index: number) => {
const factory = this._resolver.resolveComponentFactory(
this.tabs[index].component);
vcr.createComponent(factory);
}
)
}
}
p.s.可以使用生命周期挂钩 AfterContentInit
或
p.s. Dynamic content may be loaded using lifecycle hook AfterContentInit
or AfterViewInit
.
这篇关于角动态组件:@ViewChildren为QueryList中的每个组件获取ViewContainerRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!