OnPush 策略是 Angular 的组件检测机制之一。如果组件设置了 OnPush 策略,那么在下列情况下 Angular 才会对组件进行检测并更新视图:
- 输入属性的值发生了变化
- 调用了组件的 detectChanges() 方法
- 调用了组件所在的 NgZone 的 run() 方法
OnPush 策略可以帮助减少不必要的组件检测和视图更新,提高应用的性能。
要在组件中使用 OnPush 策略,需要在组件的 @Component 装饰器中设置 changeDetection 属性:
import { ChangeDetectionStrategy, Component } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: './my-component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
...
}