1

使用组件方法禁用 Angular 按钮是好还是坏?具体来说,这会是 Angular 中的性能问题吗?看来Angular必须不断计算。

使用静态变量(例如 this.productDisable: boolean)是否更好,让它在特定时间进行计算?

isProductSaveDisabled() {
  if (this.productsSelected == null || this.productsSelected ?.length === 0) {
    return true;
  } else {
    return false;
  }

}

HTML:

<button mat-raised-button [disabled]="isProductSaveDisabled()" (click)="saveAll()">
    Save Product
</button>

使用类方法等好奇地阅读教程和文章的战利品

4

2 回答 2

4

This is the sort of question you will get asked in job interviews and it can cost you the job so don't put a function call in the template.

The best answer would be to use a pipe

@Pipe({
  name: 'emptyArray'
})
export class EmptyArrayPipe implements PipeTransform {
  transform(array: any[]): boolean {
    return !!array || array.length === 0;
  }
}

and use it

[disabled]="productsSelected | emptyArray"

This will only trigger change detection to rerun the logic if productsSelected changes.

If you go for a lot of Angular tech interviews you are likely to encounter this kind of scenario.

于 2020-08-06T22:57:08.063 回答
-2

使用您编写它的方式,非功能版本和功能版本之间不会有任何明显的性能差异。两段代码将执行相同的次数,任何时候更改检测都需要重新评估。

值得关注的是,组件方法方法不仅让您将关注点与视图逻辑和控制器逻辑分离得更多,而且还增加了代码的可读性并引入了使用函数名称进行自我文档的机会.

于 2020-08-06T21:56:09.930 回答