Reputation: 11671
I have angular form.
When I open the app, the console is log in fooValidation
four times without me don't nothing.
in fooValidation
in fooValidation
in fooValidation
in fooValidation
Why? This is it by design? how to make it execute only after the form is submit or when focus on the specified field?
import { Component } from "@angular/core";
import { FormGroup, FormControl } from '@angular/forms';
const fooValidation = () => {
console.log('in fooValidation ');
// check two fields here
return { error: true };
}
@Component({
selector: "my-app",
template: `
<form [formGroup]="profileForm">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
</form>
`
})
export class AppComponent {
name = "Angular";
profileForm = new FormGroup({
firstName: new FormControl(""),
lastName: new FormControl("")
}, {
validators: [fooValidation]
});
}
Upvotes: 6
Views: 1279
Reputation: 79
I had the same problem, seemed to solve it by adding the group validators on the ngAfterViewChecked lifecycle hook.
public ngAfterViewChecked(): void {
myFormGroup.setValidators([validator1(), validator2()])
}
Upvotes: 1
Reputation: 12206
it is expected. validation are expected to be pretty simple, so it is usually not a problem. now why there are 4 of them:
formControlName
directive does exactly the sameUpvotes: 3