CodexBloom - Programming Q&A Platform

Angular Reactive Forms: how to to Reset Form Array After Submitting Nested Form Group

👀 Views: 284 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
angular reactive-forms form-array typescript

I'm working with Angular 12 and using Reactive Forms to manage a dynamic form which includes a FormArray of FormGroups. The form allows users to add multiple addresses, and after submission, I need to reset the entire form, including the FormArray. However, I encounter an scenario where the FormArray remains populated after calling `this.addressForm.reset()`. Here's a simplified version of my code: ```typescript import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms'; @Component({ selector: 'app-address-form', templateUrl: './address-form.component.html', }) export class AddressFormComponent implements OnInit { addressForm: FormGroup; constructor(private fb: FormBuilder) { this.addressForm = this.fb.group({ addresses: this.fb.array([]), }); } ngOnInit(): void { this.addAddress(); // Initialize with one address field } get addresses(): FormArray { return this.addressForm.get('addresses') as FormArray; } addAddress(): void { const addressGroup = this.fb.group({ street: ['', Validators.required], city: ['', Validators.required], }); this.addresses.push(addressGroup); } onSubmit(): void { if (this.addressForm.valid) { console.log(this.addressForm.value); this.addressForm.reset(); // This doesn't clear the FormArray } } } ``` In my template, I iterate over the `addresses` FormArray: ```html <form [formGroup]="addressForm" (ngSubmit)="onSubmit()"> <div formArrayName="addresses"> <div *ngFor="let address of addresses.controls; let i = index" [formGroupName]="i"> <input formControlName="street" placeholder="Street" /> <input formControlName="city" placeholder="City" /> </div> </div> <button type="button" (click)="addAddress()">Add Address</button> <button type="submit">Submit</button> </form> ``` After I submit the form, the `addresses` FormArray still contains the same controls and values. I would like the FormArray to be cleared as well. I have tried calling `this.addresses.clear()` after resetting the form, but that results in an behavior: `want to read property 'clear' of undefined`. It appears that the reference to `addresses` is lost after resetting the form. How can I effectively reset the FormArray along with the rest of the form? Any insights or best practices would be greatly appreciated!