首页 > 解决方案 > 同一个 ngFor 中不同类型的组件

问题描述

我正在从 API 获取对象。它有一个包含 2 种类型对象的数组,我必须遍历这个数组并根据每个索引处的对象呈现两个不同的组件。

两种类型的组件都需要@Inputs 和@Outputs 才能正常工作,所以我不能<ng-container>像在这个问题中显示的那样使用。

实现这样的事情的最佳方法是什么?

标签: javascriptangular

解决方案


如果您只有 2 个组件,那么您可以使用类似这样的方法来检查要呈现的组件类型:

<ng-container *ngFor="let item of items">
  <ng-container *ngTemplateOutlet="<type check condition here> ? type1 : type2; context: { $implicit: item }">
  </ng-container>
</ng-container>

<!-- in each one of these templates you can access the item in the array via "item" -->
<ng-template #type1 let-item>
  <!-- render component for type 1 here -->
</ng-template>

<ng-template #type2 let-item>
  <!-- render component for type 2 here -->
</ng-template>

ngSwitch如果将来组件类型的数量增加,您可能还想调查一下。


推荐阅读