Coding exercise: create a login form with validation in Angular.

Angular practical coding · Freshers

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

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