I am using Reactive form in project and I have this strange behaviour about form group validator. I made a sample example to show you the problem
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>
The output is
hello app.component.ts:18
hello app.component.ts:18
hello app.component.ts:18
hello app.component.ts:18
My question why the validator was called 4 times in this case?
The validator is running every time the control in rendered on the UI and once when it is applied as a validator on the formGroup. You can verify this by removing the controls on UI.
I used your example and found that when the application loads, the validator is called for:
You can reproduce this by commenting out the entire html with the form, and then returning it in parts and see the result in the process.
I think this is wrong behavior, but Angular works this way. I tested with version 7.1.0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With