如何在 ngFor 中为每个元素显示不同的图标?

How can I display a different icon for each element in ngFor?

我使用 ngFor 遍历设备列表,然后在 table 中显示设备。我想在与元素对应的设备名称旁边显示一个图标。例如,如果元素是 "mobile phone",那么将有一个移动图标,而下一个元素,相机,将有一个相机图标。

<tbody>
  <tr *ngFor="let item of deviceTypes"> 
    <td>{{ item.nameEn }}</td>
    <td style="text-align:center">
    <button class="btn btn-outline-primary" title="View" 
    (click)="viewDevice(item._id, item.nameEn)">
        <i class="fa fa-eye clickable"></i>&nbsp;{{
        'btn_elements.view' | translate }}</button>
    </td>
  </tr> 
</tbody>

您可以在您的项目中使用图标名称 属性:

item.icon = 'camera';

然后设置图标class:

<i class="fa clickable" [ngClass]="item.icon"></i>

或:

在函数内做映射:

<i class="fa clickable" [ngClass]="getIcon(item._id)"></i>

icons = new Map([[1, 'camera'], [2, 'phone']);

getIcon(deviceId: string): string {
   return this.icons.get(deviceId);
}