Ado*_*adh 8 angular angular-reactive-forms angular-forms
我在项目中使用反应式表单,我对表单组验证器有这种奇怪的行为。我做了一个示例来向你展示这个问题
export class AppComponent {
detailsForm: any;
constructor(private formBuilder: FormBuilder) {
this.detailsForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required]
}, { validator: [this.ValidForm] });
}
ValidForm = (formGroup: AbstractControl) => {
console.log('hello');
}
}
<form [formGroup]="detailsForm" action="" id="maforme">
<input type="text" formControlName="firstName">
<input type="text" formControlName="lastName">
<button type="button">Save</button>
</form>
Run Code Online (Sandbox Code Playgroud)
输出是
hello app.component.ts:18
hello app.component.ts:18
hello app.component.ts:18
hello app.component.ts:18
Run Code Online (Sandbox Code Playgroud)
我的问题为什么在这种情况下验证器被调用了 4 次?
每次控件在 UI 上呈现时以及在 formGroup 上作为验证器应用时,验证器都会运行一次。您可以通过删除 UI 上的控件来验证这一点。
| 归档时间: |
|
| 查看次数: |
2872 次 |
| 最近记录: |