Skip to content

Lab 01: Reactive Forms

step-1-album-wholesale-v16-pre-add-album

In this lab, you’ll create a reactive form for adding albums using FormGroup and FormControl. You’ll bind the form to a template with Angular Material components and display validation errors.

Create a FormGroup with FormControls:

import { FormGroup, FormControl, Validators } from '@angular/forms';
albumForm = new FormGroup({
name: new FormControl('', Validators.required),
artist: new FormControl('', Validators.required),
price: new FormControl(0, [Validators.required, Validators.min(0)])
});

Use [formGroup] and formControlName:

<form [formGroup]="albumForm" (ngSubmit)="saveAlbum()">
<input matInput formControlName="name">
<input matInput formControlName="artist">
<input matInput formControlName="price" type="number">
<button type="submit" [disabled]="!albumForm.valid">
Add Album
</button>
</form>

Show errors conditionally:

<mat-error *ngIf="albumForm.get('name')?.hasError('required')">
Name is required
</mat-error>