implementing Form Submission in Angular: Validation scenarios for Conditional Fields
I'm trying to debug I'm working with an scenario with my Angular 14 application where I'm using reactive forms to handle a complex input scenario. I have a form with several conditional fields, and I'm trying to validate them based on user input. The question is that when I submit the form, the validation message for one of the conditional fields is not triggering as expected, even though the field is marked as required. Here's a snippet of my form setup: ```typescript import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-my-form', templateUrl: './my-form.component.html' }) export class MyFormComponent implements OnInit { myForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ name: ['', Validators.required], email: ['', [Validators.required, Validators.email]], subscribe: [false], additionalInfo: [''] }); } ngOnInit() { this.myForm.get('subscribe').valueChanges.subscribe(value => { if (value) { this.myForm.get('additionalInfo')?.setValidators(Validators.required); } else { this.myForm.get('additionalInfo')?.clearValidators(); } this.myForm.get('additionalInfo')?.updateValueAndValidity(); }); } onSubmit() { if (this.myForm.valid) { console.log('Form Submitted!', this.myForm.value); } else { console.log('Form is invalid!', this.myForm.errors); } } } ``` In the template, I have something like this: ```html <form [formGroup]='myForm' (ngSubmit)='onSubmit()'> <input formControlName='name' placeholder='Name' /> <input formControlName='email' placeholder='Email' /> <label> <input type='checkbox' formControlName='subscribe' /> Subscribe to additional info </label> <div *ngIf='myForm.get("subscribe")?.value'> <input formControlName='additionalInfo' placeholder='Additional Info' /> <div *ngIf='myForm.get("additionalInfo")?.errors?.required'>This field is required when subscribing.</div> </div> <button type='submit'>Submit</button> </form> ``` Despite setting the validators correctly, I'm observing that when I check the 'Subscribe' checkbox, the 'Additional Info' field is still allowing submission without being filled in. I even added console logs to check the state of the validators and the form, and it seems like the validators are not being applied as expected. Has anyone encountered a similar scenario? Any suggestions on how to ensure that the conditional validation works as intended? I've been using Typescript for about a year now. How would you solve this? For context: I'm using Typescript on Linux. What are your experiences with this?