Reputation: 5235
I have an Angular Reactive Form with child component inputs with custom validator.
I got a strange behavior:
When I select an input the first time then I put value that invalidates the field, I don't get red borders but I see that the form control in not valid. the borders changes color only when I unfocus the field. Then when I go back on it and update values I get "live" UI validations of the inputed text every caracter change.
export class FormFieldErrorExample {
email = new FormControl('', [Validators.required, Validators.email]);
getErrorMessage() {
if (this.email.hasError('required')) {
return 'You must enter a value';
}
return this.email.hasError('email') ? 'Not a valid email' : '';
}
}
Html
<div class="example-container">
<mat-form-field appearance="fill">
<mat-label>Enter your email</mat-label>
<input matInput placeholder="[email protected]" [formControl]="email" required>
<mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
</mat-form-field>
</div>
An example in the official angular material site at the email
What I need is to change input validation style starting from first focus.
Upvotes: 2
Views: 2876
Reputation: 5235
I found a solution , When I build the form dynamically , I have added the property markAllAsTouched()
to the formGroup .
Now when I put a wrong value for the first time I get directly the input with red borders without the need to unfocus it to see wether my text is valid or not.
I don't know if it's the best solution. I'm interested still in other vision
Upvotes: 2