首页 > 解决方案 > 在 Angular 中将条件渲染逻辑放在哪里?

问题描述

我正在开发一个组件,我需要根据状态显示不同的图标:

组件.html

<app-form-row label="Status">
    <span>
      <i *ngIf="getStatus === 'READY'" class="check circle outline icon green"></i>
      <i *ngIf="getStatus === 'UPDATING'" class="notched circle loading icon orange"></i>
      <i *ngIf="getStatus === 'FAILED'" class="times circle outline icon red"></i>
    </span>
</app-form-row>

组件.ts

get getStatus(): string {
    return this.data.status;
  }

另一种方法是在 TS 中移动条件。

组件.html

<app-form-row label="Status">
    <span>
      <i [ngClass]=“classByStatus"></i>
    </span>
</app-form-row>

组件.ts

get classByStatus(): string {
    return {
      'READY': 'check circle outline icon green',
      'UPDATING': 'notched circle loading icon orange',
      'FAILED': 'times circle outline icon red'
    }[this.data.status];
  }

每种方法的优缺点是什么?
还有其他方法可以解决此用例吗?

标签: htmlangulartypescript

解决方案


TBH,两者都是不好的方法。使用默认更改检测策略将函数绑定到指令(以及模板插值{{ }})将触发每个更改检测周期的函数。最初可能不是一个大问题,但以后可能会导致性能问题。

理想的解决方案是直接在ngClass

<i
  class="circle icon"
  [ngClass]="{
    'READY': 'check outline green', 
    'UPDATING': 'notched loading orange', 
    'FAILED': 'times outline red'
  }[data.status]"
>
</i>

推荐阅读