角度变化检测运行八次而不是四次

ng2*_*ser 2 javascript angular

我知道如果我们正在开发Angular运行两次更改检测.在以下示例中,Angular运行四次更改检测.为什么会这样?

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 {}
Run Code Online (Sandbox Code Playgroud)

如果您运行上面的代码,您将看到控制台日志运行八次而不是四次.

yur*_*zui 9

我知道它没有记录,但是appRef.tick在引导应用程序时,angular会额外运行

 private _loadComponent(componentRef: ComponentRef<any>): void {
    this.attachView(componentRef.hostView);
    this.tick();
Run Code Online (Sandbox Code Playgroud)

https://github.com/angular/angular/blob/4.3.x/packages/core/src/application_ref.ts#L540

然后它调用主处理程序来运行更改检测

this._zone.onMicrotaskEmpty.subscribe(
    {next: () => { this._zone.run(() => { this.tick(); }); }});
Run Code Online (Sandbox Code Playgroud)

https://github.com/angular/angular/blob/4.3.x/packages/core/src/application_ref.ts#L445

tick方法角运行detectChanges方法期间

this._views.forEach((view) => view.detectChanges()); 
Run Code Online (Sandbox Code Playgroud)

https://github.com/angular/angular/blob/master/packages/core/src/application_ref.ts#L561

并以开发模式 changeNoChanges

if (this._enforceNoNewChanges) {
    this._views.forEach((view) => view.checkNoChanges());
}
Run Code Online (Sandbox Code Playgroud)

https://github.com/angular/angular/blob/master/packages/core/src/application_ref.ts#L563

因此角度运行在第一次初始化时改变检测4次.

因为你在模板中使用了两次getter

[value]="option.id">{{option.id}}
Run Code Online (Sandbox Code Playgroud)

它会执行两次,最后你会得到8个电话