首页 > 解决方案 > 如何在角度 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';
      }
   }
 }

我尝试过这种方式,但它为所有项目应用了相同的图标。如果有人告诉我如何解决这个问题?

标签: typescriptangular8

解决方案


每个元素都有相同的图标,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>

推荐阅读