我知道如果我们在开发 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/