Angular 16 - Form Array with Conditional Validators Not Behaving as Expected
I'm collaborating on a project where Does anyone know how to Hey everyone, I'm running into an issue that's driving me crazy..... I'm working on an Angular 16 application and have a dynamic form that includes a FormArray. Each FormGroup within the FormArray has some conditional validators that are supposed to activate based on the value of a specific control. However, I'm working with unexpected behavior where the validators sometimes don't trigger as anticipated, leading to incorrect form validation states. Here's a simplified version of what my form looks like: ```typescript this.dynamicForm = this.fb.group({ items: this.fb.array([]) }); addItem() { const itemGroup = this.fb.group({ name: ['', Validators.required], age: ['', [Validators.required, Validators.min(18)]], hasPermission: [false] }); itemGroup.get('hasPermission')?.valueChanges.subscribe((hasPermission) => { if (hasPermission) { itemGroup.get('age')?.setValidators(Validators.required); } else { itemGroup.get('age')?.clearValidators(); } itemGroup.get('age')?.updateValueAndValidity(); }); this.items.push(itemGroup); } get items() { return this.dynamicForm.get('items') as FormArray; } ``` When I toggle the `hasPermission` checkbox, the age field's validators are not consistently updating. I often see the form showing as valid even when it should be invalid. I tried using `updateValueAndValidity()` after changing the validators, but it still doesn't seem to work correctly. Additionally, I'm getting this behavior in the console sometimes: `want to read properties of null (reading 'setValidators')`. This seems to happen when I remove an item from the FormArray and the subscription is still active. I've tried unsubscribing on component destruction, but the question continues. Am I missing something fundamental in my implementation, or is there a better approach to handle conditional validators in a FormArray? Any insights or suggestions would be greatly appreciated! For context: I'm using Typescript on Linux. Any ideas what could be causing this? Any help would be greatly appreciated! I'm coming from a different tech stack and learning Typescript. Is there a simpler solution I'm overlooking? What are your experiences with this? I'm using Typescript 3.11 in this project. Has anyone dealt with something similar?