CodexBloom - Programming Q&A Platform

Angular Reactive Forms: Handling Conditional Field Validation with Observables

👀 Views: 18 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
angular reactive-forms validation TypeScript

I'm struggling with implementing conditional validation in my Angular reactive form. I have a form that includes a checkbox, and depending on whether that checkbox is checked, I need to either require a second input field or remove its validation. I've tried using `setValidators` method, but the validation isn't updating correctly when the checkbox state changes. Here's a simplified version of my code: ```typescript import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-my-form', templateUrl: './my-form.component.html' }) export class MyFormComponent { myForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ checkboxField: [false], conditionalField: ['', []] }); this.myForm.get('checkboxField')?.valueChanges.subscribe((checked) => { if (checked) { this.myForm.get('conditionalField')?.setValidators([Validators.required]); } else { this.myForm.get('conditionalField')?.clearValidators(); } this.myForm.get('conditionalField')?.updateValueAndValidity(); }); } } ``` And in my HTML: ```html <form [formGroup]="myForm"> <label> <input type="checkbox" formControlName="checkboxField"> Check to require conditional field </label> <input type="text" formControlName="conditionalField" placeholder="Conditional input"> <div *ngIf="myForm.get('conditionalField')?.errors?.required">This field is required when the checkbox is checked.</div> </form> ``` However, the validation message does not appear when I check the checkbox, and I still can submit the form without entering a value in the `conditionalField`. I suspect the scenario might be with how I'm managing the validators or triggering validation updates. Any insights on how to properly implement this conditional validation? I'm using Angular version 14.0.0.