Angular 16: Issues with Dynamic FormArray Validation on Item Removal
Quick question that's been bugging me - I'm working on an Angular 16 application where I have a dynamic form that uses a `FormArray` to manage a list of items, each of which has its own validation rules. The setup works well when adding items, but Iβm facing a major issue when trying to remove an item from the `FormArray`. The relevant validation messages do not update correctly after an item is removed, leading to inconsistent user feedback. 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-dynamic-form', templateUrl: './dynamic-form.component.html', }) export class DynamicFormComponent implements OnInit { myForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ items: this.fb.array([]) }); } ngOnInit() { this.addItem(); // add one item initially } get items(): FormArray { return this.myForm.get('items') as FormArray; } addItem() { const itemGroup = this.fb.group({ name: ['', Validators.required], quantity: ['', [Validators.required, Validators.min(1)]] }); this.items.push(itemGroup); } removeItem(index: number) { this.items.removeAt(index); this.updateValidators(); // trying to re-validate } updateValidators() { this.items.controls.forEach((control) => { control.updateValueAndValidity(); }); } } ``` And in my template, I have something like this: ```html <form [formGroup]="myForm"> <div formArrayName="items"> <div *ngFor="let item of items.controls; let i = index" [formGroupName]="i"> <input formControlName="name" placeholder="Item Name" /> <input formControlName="quantity" placeholder="Quantity" /> <button (click)="removeItem(i)">Remove</button> <div *ngIf="item.get('quantity').invalid && item.get('quantity').touched"> Quantity is required and must be greater than 0. </div> </div> </div> <button (click)="addItem()">Add Item</button> <button [disabled]="myForm.invalid">Submit</button> </form> ``` When I remove an item, the validation messages for the remaining items sometimes do not refresh correctly, especially if they were previously valid and now become invalid after an item is removed. Iβve tried calling `updateValueAndValidity()` on each control after removing an item, but it doesn't seem to have the desired effect. The console does not throw any errors, but the UI remains misleading. Any suggestions on how to ensure that the validation states are correctly updated after removing an item from the `FormArray`? Thanks in advance!