CodexBloom - Programming Q&A Platform

How to implement guide with custom validation on dynamic form fields in angular reactive forms

๐Ÿ‘€ Views: 15 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-08-27
angular reactive-forms validation TypeScript

I've encountered a strange issue with I'm stuck trying to I'm learning this framework and I tried several approaches but none seem to work... I'm working with an scenario with custom validation on dynamic fields in an Angular Reactive Form. I have a form that dynamically adds and removes fields based on user input, but the custom validators I set up donโ€™t seem to trigger correctly on the newly added fields. Here's a simplified version of my setup: ```typescript import { Component } from '@angular/core'; import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-dynamic-form', templateUrl: './dynamic-form.component.html', }) export class DynamicFormComponent { myForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ fields: this.fb.array([]) }); } get fields() { return this.myForm.get('fields') as FormArray; } addField() { const fieldGroup = this.fb.group({ name: ['', [Validators.required, this.customValidator]], }); this.fields.push(fieldGroup); } removeField(index: number) { this.fields.removeAt(index); } customValidator(control: AbstractControl) { return control.value.length < 3 ? { 'minLength': true } : null; } } ``` In my template, I'm using `*ngFor` to iterate over the `fields` array: ```html <form [formGroup]='myForm'> <div formArrayName='fields'> <div *ngFor='let field of fields.controls; let i = index' [formGroupName]='i'> <input formControlName='name' /> <div *ngIf='field.get("name")?.errors?.minLength'>Field must be at least 3 characters.</div> <button (click)='removeField(i)'>Remove</button> </div> </div> <button (click)='addField()'>Add Field</button> <button [disabled]='myForm.invalid'>Submit</button> </form> ``` The question is that when I add new fields, the custom validator for those fields doesn't seem to be firing upon input. If I manually trigger validation by calling `updateValueAndValidity()`, then it works, but I would prefer it to be reactive without additional calls. Iโ€™ve tried using `setValidators` after adding the field, but that doesnโ€™t seem to help either. I also verified that the form controls are being initialized correctly and that the validation logic is sound. What could be going wrong here? Is there a best practice for ensuring dynamic fields trigger their validators as expected? I'm working on a service that needs to handle this. Any help would be greatly appreciated! Thanks for taking the time to read this! I'm working on a CLI tool that needs to handle this. Is this even possible?