gpt4 book ai didi

Angular 动态组件 : @ViewChildren get ViewContainerRef for every component in QueryList

转载 作者:行者123 更新时间:2023-12-03 21:18:27 26 4
gpt4 key购买 nike

我正在构建一个带有动态选项卡的对话框,该对话框可以接收要放置在选项卡正文中的组件。我很难使用@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

最佳答案

@ViewChildren 由于缺少 read 组件中的组件不起作用指示 ViewContainerRef 的元数据属性.
零件

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.可以使用生命周期 Hook AfterContentInit 加载动态内容或 AfterViewInit .

关于 Angular 动态组件 : @ViewChildren get ViewContainerRef for every component in QueryList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57721310/

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