如何在循环内注入组件

问题描述 投票:0回答:1

我们可以动态注入 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
]
angular angular2-template
1个回答
0
投票

您可以使用ngComponentOutlet。 https://angular.io/api/common/NgComponentOutlet

示例:

@for (component of components; track $index) {
    <ng-container *ngComponentOutlet="component"></ng-container>
}
© www.soinside.com 2019 - 2024. All rights reserved.