可能会出现这个问题的原因是在监听表单控件的值变化时,代码同时更改了表单控件的值,导致了无限循环。为了避免这个问题,可以将更改控制器值的代码放在Angular的zone之外,使其避开Angular的变更检测。
示例代码:
import { Component, NgZone } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
Form value: {{ formGroup.value | json }}
`,
})
export class AppComponent {
formGroup = new FormGroup({
name: new FormControl('')
});
constructor(private ngZone: NgZone) {
this.formGroup.get('name').valueChanges.subscribe(name => {
// This code will cause an infinite loop
// this.formGroup.setValue({ name: name.toUpperCase() });
// Putting the code outside of Angular zone
// will avoid the infinite loop
this.ngZone.runOutsideAngular(() => {
this.formGroup.setValue({ name: name.toUpperCase() });
});
});
}
}