Skip to main content

Lab 02: FormArray for Tags

πŸ“– Resources​

πŸš€ Starter Code​

step-2-album-wholesale-v16-post-add-album

In this lab, you'll add dynamic tag management to the album form using FormArray. You'll implement methods to add and remove form controls dynamically, allowing users to create multiple tag inputs on the fly.

πŸ“ Instructions​

Step 1: Add FormArray to Form​

Add a FormArray for dynamic fields:

import { FormBuilder, FormArray } from '@angular/forms';

private fb = inject(FormBuilder);

albumForm = this.fb.group({
name: ['', Validators.required],
artist: ['', Validators.required],
tags: this.fb.array([]) // FormArray for tags
});

get tags(): FormArray {
return this.albumForm.get('tags') as FormArray;
}

Step 2: Add/Remove Items​

Methods to manage FormArray:

addTag() {
this.tags.push(this.fb.control('', Validators.required));
}

removeTag(index: number) {
this.tags.removeAt(index);
}

Step 3: Template with FormArray​

Iterate over FormArray in template:

<div formArrayName="tags">
<div *ngFor="let tag of tags.controls; let i = index">
<input [formControlName]="i" placeholder="Tag">
<button type="button" (click)="removeTag(i)">Remove</button>
</div>
<button type="button" (click)="addTag()">Add Tag</button>
</div>