Introduction
In this article, we will learn how to use ChangeDetectionStrategy.OnPush
in Angular to improve the performance of your application. By default, Angular uses ChangeDetectionStrategy.Default
, which means that the change detection runs every time an event is triggered in the application. This can be inefficient if your application has a lot of components that don’t need to be updated every time an event is triggered. By using ChangeDetectionStrategy.OnPush
, you can tell Angular to only run change detection on a component when its input properties change. with onPush
strategy, Angular will only trigger change detection in the following cases:
- When component’s input property changes
- When an event is triggered in the component
- When you manually trigger change detection
- 注意:这里好像还有一条是async pipe,但是我找不到文档了,以后找到再补充吧。
Example
Take a look at the product
component below, it has an input property name
, and an event handler which changes the price of the product. We have set the changeDetection
property to ChangeDetectionStrategy.OnPush
in the component’s metadata.
1 | <!-- product.component.html --> |
1 | ({ |
- When parent component change the input property
name
, Angular will trigger change detection in theproduct
component. and console will outputchange detection triggered...
- When user click button to change the price, Angular will trigger change detection in the
product
component. and console will outputchange detection triggered...
setTimeout
function will not trigger change detection in theproduct
component.
Change Detection with OnPush Diagram
See here for details.
Do I need OnPush
strategy if component has no @Input
bindings?
Yes, OnPush
still make sense even if the component has no @Input
bindings.
- With
OnPush
, change detection still triggers when an event is triggered in the component. - With
OnPush
, you prevent the change detection running automatically when the parent component changes. - With
OnPush
, you can manually trigger change detection when needed withChangeDetectorRef.detectChanges()
, orChangeDetectorRef.markForCheck()
.
OnPush
+ signal is the future of Angular.