Angular Forms come with built-in validators and can display validation errors.
typescript
// component.ts
userForm = this.fb.group({
username: ['', [
Validators.required,
Validators.minLength(4),
Validators.maxLength(20)
]],
password: ['', [
Validators.required,
Validators.minLength(8)
]]
});
get username() {
return this.userForm.get('username');
}
// component.html
<form [formGroup]="userForm">
<div>
<input formControlName="username" placeholder="Username">
<div *ngIf="username?.invalid && username?.touched">
<small *ngIf="username?.errors?.['required']">
Username is required
</small>
<small *ngIf="username?.errors?.['minlength']">
Username must be at least 4 characters
</small>
</div>
</div>
<button [disabled]="userForm.invalid">Submit</button>
</form>You should see
(If the user types invalid data into a form field, error messages will show up)