我们可以动态注入 Angular 组件
ViewContainerRef.createComponent()
,其中 ViewContainerRef
指的是这样的模板引用 <ng-template #ref>
我们怎样才能实现相同的方法,但是当模板引用在循环内创建时,像这样
@for(item of items; track item){
<div>
<!-- some nested markups -->
<!-- inject each item's component here -->
<!-- this should be created several times, once for each item -->
<ng-template #ref></ng-template>
</div>
}
items = [
component1,
component2
]
您可以使用ngComponentOutlet。 https://angular.io/api/common/NgComponentOutlet
示例:
@for (component of components; track $index) {
<ng-container *ngComponentOutlet="component"></ng-container>
}