Reputation: 1222
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?
Upvotes: 11
Views: 6034
Reputation: 2858
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.
Upvotes: 3
Reputation: 5321
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.
Upvotes: 3
Reputation: 623
I think , you need to replace AbstractControl with FormGroup in this line - ValidForm = (formGroup: AbstractControl).
Upvotes: -2