CodexBloom - Programming Q&A Platform

Angular 16 - implementing Dynamic Form Validation on Nested FormGroups

๐Ÿ‘€ Views: 79 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-03
angular reactive-forms form-validation TypeScript

I'm working on a personal project and I'm currently working on an Angular 16 application where I'm using Reactive Forms to create a complex form with nested FormGroups. The form consists of several dynamically generated fields based on user input. I've noticed that when I add new FormGroups dynamically, the validators I apply to these groups do not seem to trigger correctly on form submission or value changes. Hereโ€™s a simplified version of what Iโ€™ve implemented: ```typescript this.form = this.fb.group({ user: this.fb.group({ name: ['', Validators.required], age: ['', [Validators.required, Validators.min(18)]], addresses: this.fb.array([]) }) }); addAddress() { const addressGroup = this.fb.group({ street: ['', Validators.required], city: ['', Validators.required] }); (this.form.get('user.addresses') as FormArray).push(addressGroup); } ``` When I call `addAddress()`, the new address FormGroup is added, but when I submit the form, the validation does not trigger for these newly added controls. I'm getting the following behavior message in the console: `behavior behavior: want to read properties of null (reading 'get')` I've tried explicitly setting the validators after adding the new FormGroup and even marked the FormArray as dirty to force validation, but nothing seems to work. Hereโ€™s how I'm attempting to submit the form: ```typescript onSubmit() { if (this.form.valid) { console.log(this.form.value); } else { this.form.markAllAsTouched(); console.log('Form is invalid', this.form.errors); } } ``` What am I missing here? Is there a better way to handle dynamic validations for nested FormGroups in Angular Reactive Forms? Any insights or examples would be greatly appreciated!