html - 在 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];
}
每种方法的优缺点是什么?
还有其他方法可以解决此用例吗?
解决方案
TBH,两者都是不好的方法。使用默认更改检测策略将函数绑定到指令(以及模板插值{{ }}
)将触发每个更改检测周期的函数。最初可能不是一个大问题,但以后可能会导致性能问题。
理想的解决方案是直接在ngClass
<i
class="circle icon"
[ngClass]="{
'READY': 'check outline green',
'UPDATING': 'notched loading orange',
'FAILED': 'times outline red'
}[data.status]"
>
</i>
推荐阅读
- excel - 我找不到颜色列中的值与 id 列中的相同 id 匹配的次数。?
- nlp - 如何改进我的 nlp 模型以对 4 种不同的精神疾病进行分类?
- java - 由于空检查,使用 lambda 优化 if else 语句?
- python - 如何在 Django 中执行 PostgreSQL 查询
- c# - 如何从xml中删除列表父节点?
- r - 如何记录重复 ID 的不同值
- python - 如何更改 Pandas 数据框的形状
- hadoop - MacBook Air M1 上的 VirtualBox
- java - 基于给定参数在Java中打印arraylist的特定元素
- c++ - InverseSize4.h 中 4x4 矩阵逆的特征编译警告