Skip to main content

Lab 01: Reactive Forms

πŸ“– Resources​

πŸš€ Starter Code​

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.

πŸ“ Instructions​

Step 1: Create FormGroup​

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)])
});

Step 2: Bind Form to Template​

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>

Step 3: Display Validation Errors​

Show errors conditionally:

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