Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

javascript - Angular change detection runs eight times instead four

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...