javascript - Angular 变化检测运行八次而不是四次

标签 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 {}

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

最佳答案

我知道它没有记录,但 angular 运行附加 appRef.tick引导应用程序时

 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

然后它调用主处理程序来运行更改检测
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

期间tick方法 Angular 运行 detectChanges方法
this._views.forEach((view) => view.detectChanges()); 

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

并在开发模式 changeNoChanges
if (this._enforceNoNewChanges) {
    this._views.forEach((view) => view.checkNoChanges());
}

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

因此,angular 在第一次初始化时运行了 4 次更改检测。

由于您在模板中使用了两次 getter
[value]="option.id">{{option.id}}

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

关于javascript - Angular 变化检测运行八次而不是四次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45412199/

相关文章:

angular - 组件 "AppFooterComponent"的选择器应该用作元素

javascript - 比较 JavaScript 数组

javascript - Ajax 调用或 php 脚本向我的数据结果添加空格

javascript - 多维数组的后续排序会产生意想不到的结果

javascript - 比较相等的对象给出错误,javascript

angular - 在 Angular 中从模板中引用属性或 getter 的性能

angular - 如何在angular6中使用 typescript 获取当前年份

angular - 无法在 Angular 2 中的 *ngFor 中找到变量

javascript - 如何触发两个函数,一个是在页面重新加载/刷新另一个函数时触发?

angular - 进行深度复制还是不进行深度复制-无论如何,为什么ngrx的状态应该是不可变的?