【发布时间】:2020-01-03 09:18:09
【问题描述】:
我正在构建一个带有动态选项卡的对话框,该对话框可以接收要放置在选项卡正文中的组件。我很难使用@ViewChildren 创建多个动态组件。我过去很容易用单个组件和@ViewChild 成功地做到了这一点。
这是我的模板:
<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,但我不确定为什么它根本没有填充。我用这个帖子作为参考:Post
【问题讨论】:
-
尝试使用 ngAfterViewInit。无论如何-我必须检查一下-我认为如果在 AfterViewInit 发生时您的模板不在视图中,您需要订阅
this.dynComponents.changes.subscribe(res=>{..here you has your dnyComponent..}
标签: angular angular-dynamic-components