typescript - 如何在角度 8 中使用 *ngFor 根据 API 响应显示不同的不同图标?
问题描述
在我的项目中,我正在使用 angular 最新版本,我获取了一个 API 并得到了一些响应,因此我使用了 *ngFor 并在模板(HTML)mat-dropdown 中显示了角度材料中的数据。现在我的问题是基于 API 响应如何在文本之前显示图标?
在我的 API 响应中,我有操作系统类型,基于操作系统,我必须显示该图标。
*ngFor 条件:
<mat-option
*ngFor="let item of activeItems">
<i *ngIf="hasIcon" class="fa-{{iconType}}"></i>
<span [textContent]="item.name"></span>
</mat-option>
图标条件:
public items: Page<PageObject>;
public iconType;
getItems() {
if(this.hasIcon == true ){
if(this.items.content.filter((item: PageObject) => item['andriod'])) {
this.iconType = 'andriod';
} else if(this.items.content.filter((item: PageObject) => item['ios'])) {
this.iconType = 'ios';
}
}
}
我尝试过这种方式,但它为所有项目应用了相同的图标。如果有人告诉我如何解决这个问题?
解决方案
每个元素都有相同的图标,mat-option
因为它对iconType
每个元素使用相同的属性。可能的解决方案是使用数组而不是单个值。此外,您可以创建一个方法,该方法将基于item
.
组件中有这样的东西
getIconType(item: PageObject): string {
return item['andriod'] ? 'andriod' : 'ios';
}
模板中的用法
<mat-option *ngFor="let item of activeItems">
<i *ngIf="hasIcon" class="fa-{{ getIconType(item) }}"></i>
<span [textContent]="item.name"></span>
</mat-option>
推荐阅读
- asp.net-core - 如何在 Core 中获得经典的路由约定?
- java - 基于关键的 java 流将 HashMap 列表分组到 HashMap 列表
- geojson - 有没有办法将geojson坐标转换为纬度和经度?
- c# - 为什么 ListBox.DisplayMember 接受字符串值?
- javascript - 访问令牌错误 - 获取用户配置文件的图形 API
- python - 如何从列表中复制一些元素,这样就不会影响复制列表中元素的值
- java - xpath.evaluate 可以从节点(列表)获取输入吗?
- php - Laravel 外部类文件
- ios - iOS Swift 如何同步图表绘制线条、渐变和圆形动画?
- haskell - 如何处理一元返回值`m (Maybe Foo)`?