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]
});
}
stackblitz example
When the user changes the value in the watched field, the control is marked as "dirty" When the user blurs the form control element, the control is marked as "touched"
Angular does not provide built-in type async Validation implmentation, it provides only for sync validation. The implementation of async validator is very similar to the sync validator. The only difference is that the async Validators must return the result of the validation as an observable or as Promise.
It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like value , valid , and dirty . It shouldn't be instantiated directly.
Custom Validators for template-driven forms. Comparing validation in template-driven vs reactive forms. Form-level (multi-field) Validators. Asynchronous Validators.
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 sameIf 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