1 回答

TA貢獻1780條經(jīng)驗 獲得超1個贊
編輯:
通過非靜態(tài)獲取所有 templateRefs,您可以遍歷模板 refs 并為每個組件創(chuàng)建一個組件,之后您只需要將其附加到某個 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
添加回答
舉報