I am using Angular 8 and I am trying to create a registration form with reactive forms. I had created some alert messages to show validation errors.
However, the previous alert is shown instead of the current alert! (one step late)
app.component.ts file:
import { Component } from '@angular/core';
import { FormBuilder, Validators, FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
form = this.fBuilder.group({
userName: ['', [
Validators.required,
Validators.minLength(3),
this.userNameValidation.bind(this)
]]
});
requiredError: boolean;
minLengthError: boolean;
constructor(private fBuilder: FormBuilder) { }
// User Name Validation
userNameValidation(control: FormControl) {
if (control.hasError('required') && control.dirty) {
this.requiredError = true;
} else {
this.requiredError = false;
}
if (control.hasError('minlength') && control.dirty) {
this.minLengthError = true;
} else {
this.minLengthError = false;
}
}
}
app.component.html file:
<form [formGroup]="form">
<label>User Name: </label>
<input formControlName="userName" type="text">
</form>
<!-- alerts -->
<p *ngIf="requiredError">User Name is required</p>
<p *ngIf="minLengthError">User Name must be at least 3 characters</p>
Here is a simple StackBlitz showing what I mean:
Try typing one letter, then delete it and see what happens.
Thanks in advance!