Angular 15 Reactive Forms: Unexpected Behavior with Dynamic FormArray and Validators
Does anyone know how to I'm facing an issue with Angular 15 where I'm trying to dynamically add FormControls to a FormArray, but the validation isn't behaving as expected... I have a reactive form that consists of a FormArray called `items`. When I add a new FormGroup to this FormArray, I want to apply a required validator to a specific control in that group. However, after adding the control, it seems that the validation is not being triggered correctly, and I can submit the form even when the required fields are empty. Here's a snippet of my code: ```typescript import { Component, OnInit } from '@angular/core'; import { FormArray, FormBuilder, FormGroup, 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({ items: this.fb.array([]) }); } ngOnInit() { this.addItem(); } get items(): FormArray { return this.form.get('items') as FormArray; } addItem() { const itemGroup = this.fb.group({ name: ['', Validators.required], value: [''] }); this.items.push(itemGroup); } onSubmit() { if (this.form.valid) { console.log(this.form.value); } else { console.log('Form is invalid!'); } } } ``` In my template, I'm iterating over the FormArray and displaying each control: ```html <form [formGroup]="form" (ngSubmit)="onSubmit()"> <div formArrayName="items"> <div *ngFor="let item of items.controls; let i = index" [formGroupName]="i"> <input formControlName="name" placeholder="Enter name" /> <input formControlName="value" placeholder="Enter value" /> </div> </div> <button type="button" (click)="addItem()">Add Item</button> <button type="submit">Submit</button> </form> ``` I've checked that the `Validators.required` is being applied correctly to the `name` control, but when I leave it empty and submit the form, it still logs the form as valid. I've also tried calling `this.form.updateValueAndValidity()` after adding the FormGroup, but it didn't help. Is there something I'm missing in the setup? Why is the validation not working as I'm expecting it to? I'm developing on Debian with Typescript. Has anyone else encountered this?