【问题标题】:How to avoid using function in ngStyle or ngClass?如何避免在 ngStyle 或 ngClass 中使用函数?
【发布时间】:2019-10-21 21:09:49
【问题描述】:

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

30 秒内 3511 条消息(方法调用),仅针对 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 是否是一个好的解决方案,因为现在,我无法在控制台中看到这将执行多少次。哪个是最好的解决方法?

【问题讨论】:

  • 如果可能的话,可以在渲染到视图之前进行预定义的计算。
  • 你可以使用管道来减少函数调用
  • 我知道使用管道,它的行为是一样的。对于每个鼠标事件,都会执行管道
  • 你试过purepipe吗? dzone.com/articles/…

标签: angular styles ng-class ng-style


【解决方案1】:

一般而言,您可以“映射”您的数组并将其转换为对象数组,例如

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 多次你的数组“值”中的元素

【讨论】:

    猜你喜欢
    • 2022-12-14
    • 2020-04-30
    • 2021-11-14
    • 2016-07-14
    • 1970-01-01
    • 2016-07-17
    • 2020-01-17
    • 1970-01-01
    • 2018-08-28
    相关资源
    最近更新 更多