如何避免在 ngStyle 或 ngClass 中使用函数?

How to avoid using function in ngStyle or ngClass?

如果我可以这么说的话,这是一个烦人的问题......如果我在模板中使用一个方法,这将被调用很多次......由于 Angular 的变化检测。

3511 条消息(方法调用)在短短 30 秒内,仅针对 12 个项目。

我的代码最初看起来如何: html:

<td *ngFor="let value of values"
      class="value">
    <span [ngStyle]="getValueStyle(value)">{{value}}</span>
  </td>

.ts:

getValueStyle(value: any) {
console.log(value);
let stringValue = value.toString();
if (!stringValue.includes('%')) return '';

let index = stringValue.indexOf('%');
let formatedNumber = stringValue.substring(0, index).replace(/\s/g, '');
let numberValue = Number(formatedNumber);
if (Number.isNaN(numberValue) || numberValue == 0) {
  return {'color': '#585858'};
} else if (numberValue > 0) {
  return {'color': '#009900'};
} else if (numberValue < 0) {
  return {'color': '#cc0000'};
}

return '';

}

为了避免在模板中使用函数,我在.scss中声明了3类,并在.html中进行了验证(可以做到,因为是一个简单的比较)

<td *ngFor="let value of values"
      class="value">
    <span [ngClass]="!value.includes('%')
      ? 'neutral'
      : value.includes('-')
          ? 'negative'
          : (value == '0')
            ? 'neutral'
            : 'positive'">{{value}}</span>
  </td>

但是,如果我需要计算动态样式,如何避免这些重复调用? 无论如何,我不知道使用 ngClass 代替 ngStyle 是否是一个好的解决方案,因为现在,我无法在控制台中看到这将被执行多少次。哪个是最好的解决方法?

一般来说,您可以 "map" 您的数组并将其转换为对象数组,例如

const listValues=this.values.map(x=>{
   return {
      value:x,
      style:this.getValueStyle(x)
   }
})

并使用

<td *ngFor="let item of listValues"
      class="value">
    <span [ngStyle]="item.style">{{item.value}}</span>
  </td>

因此,只需多次调用 getValueStyle 数组中的元素 "values"