Emi*_*iel 6 angular angular-reactive-forms
我有一个FormGroup具有多个嵌套组和控件的。其中大多数包含验证器,例如Validators.required. 每当用户单击提交按钮时,我都会递归地循环遍历表单,以确保触发每个验证器并且每个控件都有效。这是通过将每个控件标记为 Touched 并调用 来完成的control.updateValueAndValidity()。
然而,这会触发valueChanged和statusChanged事件。我已向该事件添加了订阅者statusChanged,该事件应该处理任何错误,但我不希望触发,valueChanged因为该值没有更改。
是否可以在statusChanged不开火的情况下手动开火valueChanged?传递{ emitEvent: false }到updateValueAndValidity将阻止这两个事件被触发。
public ngOnInit(): void {
const form = this.formBuilder.group({
'name': ['', Validators.required],
'address': this.formBuilder.group({
'street': ['', Validators.required],
'number': ['', Validators.required]
})
});
form.valueChanges.subscribe(() => console.log('Should not fire'));
form.statusChanges.subscribe(() => console.log('Should fire'));
this.validateForm(form);
console.log(form.valid);
}
private validateForm(control: AbstractControl): void {
if (control instanceof FormControl) {
control.markAsTouched();
control.markAsDirty();
control.updateValueAndValidity();
} else if (control instanceof FormGroup) {
Object.keys(control.controls).forEach(field => {
this.validateForm(control.get(field));
});
}
}
// should print 'Should fire' and 'false' but not 'Should not fire'
Run Code Online (Sandbox Code Playgroud)
statusChanges 属性实际上是一个 EventEmitter,因此您可以将其强制转换以手动发出状态:
(<EventEmitter<any>> control.statusChanges).emit(control.status);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6416 次 |
| 最近记录: |