【发布时间】:2021-10-26 18:24:04
【问题描述】:
我从 API 获取一个对象。它有一个包含 2 种类型对象的数组,我必须遍历这个数组并根据每个索引处的对象呈现两个不同的组件。
这两种类型的组件都需要@Inputs 和@Outputs 才能正常工作,所以我不能像question 中显示的那样使用<ng-container>。
实现这样的最佳方式是什么?
【问题讨论】:
标签: javascript angular
我从 API 获取一个对象。它有一个包含 2 种类型对象的数组,我必须遍历这个数组并根据每个索引处的对象呈现两个不同的组件。
这两种类型的组件都需要@Inputs 和@Outputs 才能正常工作,所以我不能像question 中显示的那样使用<ng-container>。
实现这样的最佳方式是什么?
【问题讨论】:
标签: javascript angular
如果您只有 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。
【讨论】: