你可以用
ViewChildren
而不是
ViewChild
. 使用
观察儿童
您将获得所有
templates
在一个循环中
@ViewChildren('folderContainer', { read: ViewContainerRef }) foldersContainer: QueryList<ViewContainerRef>;
constructor(private resolver: ComponentFactoryResolver) { }
createFolder(event, index) {
const containers = this.foldersContainer.toArray()
const folderFactory = this.resolver.resolveComponentFactory(FolderComponent);
const folder = containers[index].createComponent(folderFactory);
}
HTML
<div *ngFor="let folder of folders; let i=index">
<p>{{folder}}</p>
<button (click)="createFolder($event, i)">ADD</button>
<div #folderContainer>
</div>
</div>
检查这个
demo