CodexBloom - Programming Q&A Platform

Angular Reactive Forms: How to Handle Dynamic FormArray Validation Across Nested Components?

👀 Views: 44 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
angular reactive-forms form-validation typescript

I'm trying to figure out I'm working with Angular 12 and trying to build a form with dynamic fields using a `FormArray` inside a nested component. The scenario I'm working with is that I need to validate the dynamically added fields based on certain conditions, but the validation doesn't seem to trigger correctly when the fields are added. Here's what I've done so far: In my parent component, I initialize the form group as follows: ```typescript this.myForm = this.fb.group({ items: this.fb.array([]) }); ``` Then, I have a method to add new items: ```typescript addItem() { const item = this.fb.group({ name: ['', Validators.required], quantity: [0, [Validators.required, Validators.min(1)]] }); this.items.push(item); } get items(): FormArray { return this.myForm.get('items') as FormArray; } ``` In the child component, I'm using `@Input` to receive the `FormArray` and attaching validations based on a condition: ```typescript @Input() items: FormArray; ngOnInit() { this.items.controls.forEach(control => { control.get('quantity').valueChanges.subscribe(value => { if (value > 10) { control.get('name').setValidators(Validators.required); } else { control.get('name').clearValidators(); } control.get('name').updateValueAndValidity(); }); }); } ``` However, when I dynamically add a new item, the validation for the `name` field doesn't update as expected. I get the following warning in the console: ``` behavior behavior: want to read property 'valueChanges' of undefined ``` I've tried ensuring that the child component initializes after the items have been added, but that doesn't seem to help. Is there a better way to handle dynamic validation for `FormArray` items in Angular, especially when dealing with nested components? Any insights or alternative approaches would be greatly appreciated! I'm working with Typescript in a Docker container on Windows 11. Any advice would be much appreciated.