Tuomas Toivonen
Tuomas Toivonen

Reputation: 23472

Angular 2 property binding lifecycle

What is the defined lifecycle of property binding in Angular 2? For example I have following element in my template:

<input type="radio" name="{{choice.question_id}}" value="{{choice.id}}"
                    [checked]="isSelected()"
                    (change)="select()"
                    required>

When are exactly those properties and event callbacks bound? As far as I know, there is some cycle which automatically refresh the bindings. Where I can find better explanation about that cycle?

My goal above is to make radiobutton selected by default if isSelected(). Thus polling the isSelected() after initial rendering is redundant and inefficient. How can I restrict that [checked]="isSelected() just to moment when element is first added to DOM?

Upvotes: 1

Views: 1351

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657018

Bindings are evaluated at every change detection cycle.

Change detection is run after some async execution happened. Angulars zone patches most async APIs like addEventHandler, removeEventHandler, setTimeout, ... After such events are processed Angular runs change detection and checks all expressions bound to inputs ([], {{}}).

Such events happen very frequently and thus bound expressions are evaluated very frequently. Therefore it's important to make these expressions efficient. This is one of the reasons the Angular team discourages binding to functions and to rather assign the result to a property and bind to that property instead because compairsion of properties is quite efficient, or even better, bind to observables and promises (using the | async pipe) that actively notify about changes.

You can't define at what point a binding is evaluated. It is evaluated every time change detection runs. You can control though when change detection runs on your component or its child components by setting ChangeDetectionStrategy.OnPush instead of ChangeDetectionStrategy.CheckAlways (default) and invoke change detection "manually".

In devMode default, change detection also aways runs twice to check if the first change detection turn itself didn't cause any changes in the model which is considered a bug. This needs to be taken into account if you're wondering why a bound method is called so frequently. If in devMode divide the count by 2 to get the effective number as it would happen in prodMode.

Upvotes: 2

Related Questions