【问题标题】:How to show the different different icons based on API response using *ngFor in angular 8?如何在角度 8 中使用 *ngFor 根据 API 响应显示不同的不同图标?
【发布时间】:2021-05-18 17:43:17
【问题描述】:

在我的项目中,我正在使用 angular 最新版本,我获取了一个 API 并得到了一些响应,因此我使用了 *ngFor 并在模板(HTML)mat-dropdown 中显示了 angular 材料中的数据。现在我的问题是基于 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';
      }
   }
 }

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

【问题讨论】:

    标签: typescript angular8


    【解决方案1】:

    每个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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      相关资源
      最近更新 更多