Thursday, July 14, 2016

Angular 2 change detection

Default behaviour

Change detection is fired on each event loop chance (events, http requets, timers, ...).

Components are allways explored form the root to the leafs of the component tree.

By default, A2 is conservative and explores the complete tree and evaluates all the expressions in each component or directive template. Then compares the output of each expression to its previous output. If the result of an expression has changed, A2 updates the DOM accordingly.

This is as fast as posible; A2 generates change detectors with Javascript VM-friendly code (monomorphic). As the application grows, things may start to lag.

This is the default CD strategy and is called ChangeDetectionStrategy.CheckAllways.

OnPush mode

In order to reduce the performance impact the CD strategy of components can be set to ChangeDetectionStrategy.OnPush.

OnPush means that the change detector will only run on a component or directive if one of the following occurs:
  • An input property has changed to a new value (new primitive value or new object reference).
  • An event handler fired in the component or directive (???).
  • You manually tell the change detector to look for changes.
  • The change detector of a child component or directive runs.
OnPush should be implemented starting on leafs, otherwise child components or directives on them with CheckAllways strategy won't be allways executed.


References

No comments:

Post a Comment