Angular Reactive Forms: Validation Not Triggering on Dynamic Form Array Changes
Quick question that's been bugging me - I'm building a feature where I'm relatively new to this, so bear with me. I'm working on a personal project and I'm working with Angular 14, and I'm facing an issue where validation isn't triggering correctly when I dynamically add or remove controls from a `FormArray`. I have a form where users can add multiple entries, but once a new entry is added, the required validation doesn't seem to activate until I manually blur the input or change focus. Hereโs a simplified version of the code I'm using: ```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 { form: FormGroup; constructor(private fb: FormBuilder) { this.form = this.fb.group({ entries: this.fb.array([]) }); } ngOnInit(): void { this.addEntry(); // Initialize with one entry } get entries(): FormArray { return this.form.get('entries') as FormArray; } addEntry(): void { const entry = this.fb.group({ name: ['', Validators.required], age: ['', [Validators.required, Validators.min(1)]] }); this.entries.push(entry); } removeEntry(index: number): void { this.entries.removeAt(index); } onSubmit(): void { if (this.form.valid) { console.log(this.form.value); } else { console.error('Form is invalid'); } } } ``` And hereโs the corresponding template snippet: ```html <form [formGroup]='form' (ngSubmit)='onSubmit()'> <div formArrayName='entries'> <div *ngFor='let entry of entries.controls; let i = index' [formGroupName]='i'> <input formControlName='name' placeholder='Name' /> <input formControlName='age' placeholder='Age' /> <button type='button' (click)='removeEntry(i)'>Remove</button> </div> </div> <button type='button' (click)='addEntry()'>Add Entry</button> <button type='submit'>Submit</button> </form> ``` I've tried ensuring that the validation is set on each control and checking the status of the form at various points, but the validation messages don't appear as expected until I interact with the input fields again. Iโm wondering if there's a specific way to trigger validation after adding controls dynamically or if I need to manually trigger change detection. Any insights would be greatly appreciated. For context: I'm using Typescript on Windows. Any ideas what could be causing this? For context: I'm using Typescript on Ubuntu. I recently upgraded to Typescript 3.10.