Angular 16 - implementing Dynamic Form Validation on Nested FormGroups
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!