Fernando Leal
Fernando Leal

Reputation: 10115

How does bind fields work in Angular?

I'm working on a project where performance is crucial because it's focused in working on mobile devices with few resources.

I ended up verifying that the Angular bind might not be as efficient as I expected, since I imagined that the triggers for checking a field would be through observes them themselves or checking their sets. But it seems that what is monitored for change is the entire context of the application and any changing in any instance of the context (even in isolated components) triggers a check on all the fields of the context, even if the change has no relation to it.

I created an example in plunkr to try to illustrate this behavior.

I have some questions about this behavior:

Upvotes: 3

Views: 63

Answers (2)

Milad
Milad

Reputation: 28592

In your Plunker, the text box is the child component.

When a child component has a async event that Angular has hooks in, like onKeyUp, after the event is finished, Angular will run the change detection to make sure nothing is updated in the model, but in order to achieve that, it should start from root of the application to that specific component.

So ,

if you put the input in the parent, the children's change detection won't fire if you use changeDetection:ChangeDetectionStrategy.OnPush on it.

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657018

Angular change detection is extremely efficient, especially if you consider a few things

  • only bind to fields (getters and methods are slower, especially binding to getters or methods that contain non-trivial code is usually a bad idea)
  • use ChangeDetectionStrategy.OnPush wherever possible. It reduces the work change detection does a lot
  • use observables to push changes instead of letting change detection recognize them (especially efficient with OnPush)

Upvotes: 3

Related Questions