Change detection strategies - FadiZahhar/switchingtoangular2 GitHub Wiki
you can find the code in // ch4/ts/change_detection_strategy_broken/app.ts
The change detection strategies that Angular 2 provides are: CheckOnce, Checked,
CheckAlways, Detached, Default, and OnPush. We will describe how we can
take advantage of OnPush in detail, since it is very powerful when working with
immutable data. Before taking a deep dive into OnPush, let's briefly describe the
other strategies.
Now, let's import the TypeScript enum, which can be used to configure the strategy
used for the individual components:
// ch4/ts/change_detection_strategy_broken/app.ts
import {ChangeDetectionStrategy} from 'angular2/core';
Now, we can configure the TodoList component to use the Checked strategy:
@Component({
selector: 'todo-list',
changeDetection: ChangeDetectionStrategy.Checked,
template: ...,
styles: […]
})
class TodoList { … }
This way, the change detection will be skipped until its mode (strategy) changes to
CheckOnce. But what does it mean to prevent the change detection from running?
You can go to http://localhost:5555/dist/dev/ch4/ts/change_detection_
strategy_broken/ and see the inconsistent behavior of the TodoList component.
When you add a new to-do item in the input and you click on the button, it won't
immediately appear in the list.
Now, let's try CheckOnce! Inside ch4/ts/change_detection_strategy_broken/
app.ts, change the change detection strategy of the TodoList component to
ChangeDetectionStrategy.CheckOnce. After refreshing the browser, try to add a
new to-do item. The change should not be immediately reflected because CheckOnce
will instruct the change detector to perform the check only once (in this case, during
initialization), and after that, nothing will happen.
By default, it is used in the CheckAlways mode, which as its name states, doesn't
prevent the change detector from running.
If we declare the strategy of a given component to Detached, the change detector
subtree will not be considered as a part of the main tree and will be skipped.