Angular Reactive Forms: Validation Errors Not Updating on Dynamic FormGroup Creation
I'm relatively new to this, so bear with me... Quick question that's been bugging me - I'm currently working with Angular 14 and using Reactive Forms to build a dynamic form. The goal is to add new form groups based on user input, but I'm facing an issue where the validation messages do not update correctly after creating a new FormGroup. When I dynamically create a new FormGroup and add it to the FormArray, the validation errors for that group do not appear until I manually trigger the form's `updateValueAndValidity()` method. Hereβs the relevant part 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({ formArray: this.fb.array([]) }); } ngOnInit() { this.addFormGroup(); // Initial call to add the first group } get formArray(): FormArray { return this.myForm.get('formArray') as FormArray; } addFormGroup() { const group = this.fb.group({ name: ['', Validators.required], email: ['', [Validators.required, Validators.email]] }); this.formArray.push(group); } submit() { if (this.myForm.valid) { console.log(this.myForm.value); } else { console.log('Form is invalid', this.myForm.errors); } } } ``` In the HTML, I observe that the validation messages do not show up until I submit the form at least once. Here's the relevant template code: ```html <form [formGroup]="myForm" (ngSubmit)="submit()"> <div formArrayName="formArray"> <div *ngFor="let group of formArray.controls; let i = index" [formGroupName]="i"> <label>Name:</label> <input formControlName="name" /> <div *ngIf="group.get('name').invalid && group.get('name').touched">Name is required.</div> <label>Email:</label> <input formControlName="email" /> <div *ngIf="group.get('email').invalid && group.get('email').touched">Valid email is required.</div> </div> </div> <button type="button" (click)="addFormGroup()">Add Another</button> <button type="submit">Submit</button> </form> ``` I've tried calling `this.myForm.updateValueAndValidity();` after adding a new FormGroup, but that did not resolve the validation message issue. Is there a better approach or a specific method to ensure that the validation messages appear immediately when new groups are added? Any insights would be greatly appreciated! My development environment is Linux. Any help would be greatly appreciated! This is part of a larger API I'm building. Am I missing something obvious? I'm working on a API that needs to handle this. Thanks in advance!