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>