如何仅在值变化时调用管道

问题描述 投票:0回答:1
angular primeng angular-pipe
1个回答
0
投票

发生这种情况是因为管道不纯净

纯管道:Angular 仅在检测到输入值发生纯变化时才执行纯管道。纯更改是对原始输入值(字符串、数字、布尔值、符号)的更改或更改的对象引用(日期、数组、函数、对象)。

不纯管道:Angular 在每个组件更改检测周期中执行不纯管道。不纯的管道经常被调用,就像每次击键或鼠标移动一样频繁。

来源:https://angular.io/guide/pipes

但是如果您出于任何原因确实需要管道不纯,出于性能考虑,您需要将组件更改检测策略设置为

OnPush
,并在应用更改时手动触发更改检测。

import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'awesome-component',
  templateUrl: './pda.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AwesomeComponent implements OnInit {
  constructor(
    private cd: ChangeDetectorRef,
  ) { }

  ...

  fetchData() {
    ...
    // after any data change
    this.cd.markForCheck();
    ...
  }
  ...
}
© www.soinside.com 2019 - 2024. All rights reserved.