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.