CodexBloom - Programming Q&A Platform

Angular 15: How to Handle Dynamic Form Validation with Reactive Forms Based on User Input?

👀 Views: 87 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
angular reactive-forms form-validation dynamic-forms TypeScript

I'm testing a new approach and I'm refactoring my project and After trying multiple solutions online, I still can't figure this out. I'm working on an Angular 15 application where I need to dynamically adjust form validation rules based on user input. I have a scenario where the user selects a type from a dropdown menu, and based on their selection, I need to add or remove validators to specific form controls. I've set up a reactive form using `FormBuilder`, and I can add validators to form controls during initialization. However, I'm unsure how to effectively update these validators in response to changes in the dropdown selection. Here's the relevant code snippet for my form setup: ```typescript import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-dynamic-form', templateUrl: './dynamic-form.component.html', }) export class DynamicFormComponent implements OnInit { form: FormGroup; selectedType: string; constructor(private fb: FormBuilder) { this.form = this.fb.group({ type: [''], description: [''], }); } ngOnInit() { this.form.get('type')?.valueChanges.subscribe(value => { this.selectedType = value; this.updateValidators(); }); } updateValidators() { const descriptionControl = this.form.get('description'); if (this.selectedType === 'mandatory') { descriptionControl?.setValidators([Validators.required, Validators.minLength(5)]); } else { descriptionControl?.clearValidators(); } descriptionControl?.updateValueAndValidity(); } } ``` In the template, I have a dropdown and the input for the description: ```html <select formControlName="type"> <option value="">Select Type</option> <option value="mandatory">Mandatory</option> <option value="optional">Optional</option> </select> <input formControlName="description" placeholder="Enter description" /> <div *ngIf="form.get('description')?.invalid && (form.get('description')?.dirty || form.get('description')?.touched)"> <small *ngIf="form.get('description')?.errors?.required">Description is required.</small> <small *ngIf="form.get('description')?.errors?.minlength">Description must be at least 5 characters.</small> </div> ``` The issue I'm facing is that the validators seem to be applied correctly, but they are not triggering the validation error messages as expected when switching between the dropdown options. When I select 'mandatory', the input field should show validation messages if left empty, but it doesn't. I've tried calling `updateValueAndValidity()` after setting the validators, but that doesn't seem to have an effect. What am I missing here? Are there any best practices for dynamically updating validators in Angular reactive forms that I should follow to ensure that the validation messages display correctly? My development environment is Ubuntu. Any ideas what could be causing this? I've been using Typescript for about a year now. This is part of a larger web app I'm building. I appreciate any insights!