基于此堆栈溢出帖子(Angular Dynamic Components: @ViewChildren get ViewContainerRef for every component in QueryList),我正在尝试在ngFor中添加动态组件。
问题在于,引用ng模板的ViewChildred始终未定义
这是我的模板
<div *ngFor="let service of loadedServices; let i = index;">
<accordion [closeOthers]="true">
<accordion-group panelClass="b0 mb-2">
<div accordion-heading>
<small>
<em class="fa fa-plus text-primary mr-2"></em>
</small>
<span><b>{{service.description}}</b></span>
</div>
<ng-template #serviceBookmark></ng-template>
</accordion-group>
</accordion>
</div>
这是我的组件
export class DatasourceDetailsComponent implements OnInit,AfterContentInit {
constructor(private resolver: ComponentFactoryResolver) { }
@ViewChildren('serviceBookmark', { read: ViewContainerRef })
public dynComponents: QueryList<ViewContainerRef>;
ngAfterContentInit() {
this.dynComponents.map(
(vcr: ViewContainerRef, index: number) => {
const factory =
this.resolver.resolveComponentFactory(ServiceFormComponent);
vcr.createComponent(factory);
}
);
}
}
不幸的是,在AfterContentInit中dynComponent始终是未定义的... 我在做什么错了?
谢谢
答案 0 :(得分:1)
您应该尝试使用ngAfterViewInit或setter:
components: QueryList<ViewContainerRef>;
@ViewChildren('serviceBookmark', { read: ViewContainerRef })
set dynComponents(comps: QueryList<ViewContainerRef>) {
console.log(comps);
this.components = comps;
}
这应该有效。