Coding exercise: create a login form with validation in Angular.
Model answer
Use a reactive form with built-in validators, show a message only after the field is touched, and disable the button while the form is invalid. The server must validate again.
@Component({
selector: 'app-login',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<label>Email <input type="email" formControlName="email" /></label>
@if (email.touched && email.errors) {
<p role="alert">@if (email.errors['required']) { Email is required. } @else { Enter a valid email. }</p>
}
<label>Password <input type="password" formControlName="password" /></label>
@if (password.touched && password.errors) { <p role="alert">Use at least 8 characters.</p> }
<button [disabled]="form.invalid">Log in</button>
</form>`,
})
export class Login {
form = new FormGroup({
email: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.email] }),
password: new FormControl('', { nonNullable: true, validators: [Validators.required, Validators.minLength(8)] }),
});
get email() { return this.form.controls.email; }
get password() { return this.form.controls.password; }
submit() { if (this.form.valid) console.log(this.form.getRawValue()); }
}Mention custom validators (for example confirm password) and typed forms, which give you typed values.
Tips
- Template-driven forms also work, but reactive forms are easier to test.
Practise it yourself in the React and Angular code playground.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in Angular.
- Coding exercise: create a search box with debounce in Angular.
- Coding exercise: fetch API data and display it in a table in Angular.
- Coding exercise: implement pagination in Angular.
- Coding exercise: build a parent-child communication example in Angular.
- Coding exercise: implement sorting and filtering in Angular.