出现这个问题的原因是在订阅valueChanges时没有取消上一个订阅,导致订阅出现了无限循环。
解决方法是在组件销毁时,取消订阅valueChanges。具体代码示例如下:
@Component({ selector: 'app-my-form', templateUrl: './my-form.component.html', styleUrls: ['./my-form.component.scss'] }) export class MyFormComponent implements OnInit, OnDestroy {
myForm: FormGroup; private valueChanges$: Subscription;
constructor(private formBuilder: FormBuilder) { }
ngOnInit(): void { this.myForm = this.formBuilder.group({ name: ['', Validators.required], email: ['', [Validators.required, Validators.email]], message: ['', Validators.required] });
this.valueChanges$ = this.myForm.valueChanges.subscribe(
(value) => {
// do something with form value
}
);
}
ngOnDestroy(): void { this.valueChanges$.unsubscribe(); }
}