Angular Change Detection: Default vs. OnPush

Miki Lee
2 min readApr 27, 2018

--

Change detection can be defined as synchronizing process of model and view. There are two types of change detection methods in Angular. This can be specified in the declaration of component like below.

@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})

If you do not specify, Angular will apply the default change detection method which detects changes for entire components whenever changes are made. As you know, Angular application is composed of hierarchical tree of components. During the runtime, every component gets the change detection class inside it, Angular traverses the application hierarchy from top to bottom components, if there is change, it updates DOM and renders the corresponding view.

The following figure 1 shows the difference between Default and OnPush. In this application, the component 1 is a top component while both component 2 and component 3 are child components of component 1 (Figure 2 and 3). Therefore, change detection is performed from component 1 to component 2 and component 3. When I add ‘Sweet’ into the input box, component 2 is rendered as the model changes while component 3 is not. This is the difference how the Default and OnPush works. Because the component 3 is set as OnPush, it does not affected by Angular’s default change detection, strictly, all the components under the component 3 in context of hierarchical components tree are not affected.

Figure 1. While Component 1 is root component, component 2 and 3 is child components of component 1. After adding a word, while component 2 is rendered as the model changes, component 3 is not. This is caused by different Change Detection Strategy.
Figure 2. Source codes for component 1.
Figure 3. Source codes for component 3. The only difference from component 2 is that ‘changeDetection: ChangeDetectionStrategy.OnPush’ line added.

Therefore, it might be comfortable to use Default option, however, as the application gets bigger, the complexity of change detection is going to be increased. That’s the reason why we may consider OnPush as our change detection strategy. If this is the case, how we can make component 3 detect change successfully? The next article will come for this answer. This is relevant with my previous article.

--

--

Responses (4)