1 回答
TA贡献1780条经验 获得超1个赞
编辑:
通过非静态获取所有 templateRefs,您可以遍历模板 refs 并为每个组件创建一个组件,之后您只需要将其附加到某个 DOM 元素(templateRef 的父元素)
@ViewChildren("dynamicTemplateId") private refs: QueryList<"dynamic">;
this.refs.forEach((r: any) => {
// Create a new instance of the component
const dynamicComponentRef = componentFactory.create(this.injector);
// If you don't attach to appRef ng hook cycles won't work inside the component
// You can skip adding to application ref but you'll be needing to call .detectChanges() for every changes
this.appRef.attachView(dynamicComponentRef.hostView);
// Append to parentElement since templateRef isn't a element itself
r.elementRef.nativeElement.parentElement.appendChild(dynamicComponentRef.location.nativeElement);
});
这是一个工作示例:https : //stackblitz.com/edit/angular-gmnpku?file=src/app/app.component.ts
添加回答
举报