javascript - 同一个 ngFor 中不同类型的组件
问题描述
我正在从 API 获取对象。它有一个包含 2 种类型对象的数组,我必须遍历这个数组并根据每个索引处的对象呈现两个不同的组件。
两种类型的组件都需要@Input
s 和@Output
s 才能正常工作,所以我不能<ng-container>
像在这个问题中显示的那样使用。
实现这样的事情的最佳方法是什么?
解决方案
如果您只有 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
如果将来组件类型的数量增加,您可能还想调查一下。
推荐阅读
- java - JPA eclipselink坚持没有主键但有两个外键的实体
- git - 如何从一个本地分支推送到 github 中的所有远程分支?
- javascript - (JS中的CSS)在指定尺寸时“18px”和18之间有什么区别吗
- javascript - 如何在javascript中推送数组多维
- c# - ToolTipText 在控件下弹出
- sql - 列出 SQL 中具有相同值的键
- python - 如何将函数的本地值返回到我的全局列表?
- javascript - HTML 表单方法与 jQuery 函数类型
- c# - 在 xamarin 表单应用程序上导入的 Sqlite 数据库中找不到表
- c++ - “'MinGW/bin/gcc.exe' 无法编译简单的测试程序。”