I know that if we are on development Angular runs change detection twice. In the following example, Angular runs change detection four times. Why is this happening?
class Category {
constructor( private _id ) {
}
get id() {
console.log('id');
return this._id;
}
}
@Component({
selector: 'app-select',
template: `
<select class="form-control">
<option *ngFor="let option of options;" [value]="option.id">{{option.id}}</option>
</select>
`,
})
export class SelectComponent {
@Input() options;
}
@Component({
selector: 'my-app',
template: `
<app-select [options]="options"></app-select>
`,
})
export class App {
options = [new Category(1)]
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, SelectComponent ],
bootstrap: [ App ]
})
export class AppModule {}
If you run the code above you will see that the console log runs eight times instead four.
I know it is not documented but angular runs additional appRef.tick
when bootstraping application
private _loadComponent(componentRef: ComponentRef<any>): void {
this.attachView(componentRef.hostView);
this.tick();
https://github.com/angular/angular/blob/4.3.x/packages/core/src/application_ref.ts#L540
And then it calls main handler to run change detection
this._zone.onMicrotaskEmpty.subscribe(
{next: () => { this._zone.run(() => { this.tick(); }); }});
https://github.com/angular/angular/blob/4.3.x/packages/core/src/application_ref.ts#L445
During the tick
method angular runs detectChanges
method
this._views.forEach((view) => view.detectChanges());
https://github.com/angular/angular/blob/master/packages/core/src/application_ref.ts#L561
and in dev mode changeNoChanges
if (this._enforceNoNewChanges) {
this._views.forEach((view) => view.checkNoChanges());
}
https://github.com/angular/angular/blob/master/packages/core/src/application_ref.ts#L563
So angular runs change detection 4 times on first init.
Since you use getter twice in template
[value]="option.id">{{option.id}}
it will be executed twice and finally you will get 8 calls