CodexBloom - Programming Q&A Platform

Angular Reactive Forms: FormArray Not Updating with Dynamic Field Removal

๐Ÿ‘€ Views: 1 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-10
angular reactive-forms form-array TypeScript

I'm experiencing an issue with Angular Reactive Forms where my `FormArray` does not seem to update properly when I remove a dynamic form control. I have a form set up to add multiple email addresses, but when I remove an email input field, the form state doesn't reflect the removal correctly, and the submitted value still includes the removed control. Hereโ€™s the relevant code: ```typescript import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; @Component({ selector: 'app-email-form', templateUrl: './email-form.component.html', }) export class EmailFormComponent implements OnInit { emailForm: FormGroup; constructor(private fb: FormBuilder) { this.emailForm = this.fb.group({ emails: this.fb.array([]) }); } ngOnInit() { this.addEmail(); } get emails() { return this.emailForm.get('emails') as FormArray; } addEmail() { this.emails.push(this.fb.control('')); } removeEmail(index: number) { this.emails.removeAt(index); } onSubmit() { console.log(this.emailForm.value); } } ``` The HTML template looks like this: ```html <form [formGroup]='emailForm' (ngSubmit)='onSubmit()'> <div formArrayName='emails'> <div *ngFor='let email of emails.controls; let i=index'> <input [formControlName]='i' placeholder='Email' /> <button type='button' (click)='removeEmail(i)'>Remove</button> </div> </div> <button type='button' (click)='addEmail()'>Add Email</button> <button type='submit'>Submit</button> </form> ``` When I remove an email from the array and submit the form, the console log outputs the email addresses, but it still includes the removed one. Iโ€™ve checked the form state after the removal and even ran `markAsDirty()` and `updateValueAndValidity()` on the `FormArray`, but it doesnโ€™t seem to help. Has anyone encountered this issue or can point me towards what I might be missing? I'm using Angular version 12.1.0.