Skip to content

Lab 02: FormArray for Tags

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.

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

Methods to manage FormArray:

addTag() {
this.tags.push(this.fb.control('', Validators.required));
}
removeTag(index: number) {
this.tags.removeAt(index);
}

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>