Dynamically add/remove validators in angular 12+
Today we are going to discuss how we can dynamically add/remove validators in angular. Angular dynamic validators are required when our form fields depend on each other.
For example,
We have a user form where we can fill the user information like name, email and account type. If the account type is selected as the primary account then users need to fill the security code also.
I assume that you are already familiar with angular installation and project setup. So, without extra ado let’s get straight to the point.
The html file form.component.html
<form [formGroup]="userform" (ngSubmit)="submit()"> <div class="row"> <div class="col-12 my-2"> <input class="form-control" type="text" placeholder="Enter your name" formControlName="name"> <p class="text-danger" *ngIf="userform.controls['name'].touched && userform.controls['name'].hasError('required')">Please enter the name!</p> </div> <div class="col-12 my-2"> <input class="form-control" type="email" placeholder="Enter your email" formControlName="email"> <p class="text-danger" *ngIf="userform.controls['email'].touched && userform.controls['email'].hasError('required')">Please enter the email!</p> </div> <mat-form-field appearance="fill"> <mat-label>Account type</mat-label> <mat-select formControlName="account_type"> <mat-option value="primary">Primary</mat-option> <mat-option value="secondary">Secondary</mat-option> <mat-option value="other">Others</mat-option> </mat-select> <p class="text-danger" *ngIf="userform.controls['account_type'].touched && userform.controls['account_type'].hasError('required')">Please select the account type!</p> </mat-form-field> <div class="col-12 my-2" *ngIf="primary_account"> <input class="form-control" type="text" placeholder="Enter your code" formControlName="security"> <p class="text-danger" *ngIf="userform.controls['security'].touched && userform.controls['security'].hasError('required')">Please enter the Security code!</p> </div> </div> <div class="text-left my-2"> <button class="btn btn-primary" type="submit" [disabled]="!userform.valid">Submit</button> </div> </form>
The typescript file form.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss'] }) export class FormComponent implements OnInit { userform: FormGroup; primary_account: boolean = false; constructor( private formBuilder: FormBuilder ) { this.userform = this.formBuilder.group({ name: new FormControl('', [Validators.required]), email: new FormControl('', [Validators.required, Validators.email]), account_type: new FormControl('', [Validators.required]), security: new FormControl('') }) } ngOnInit(): void { this.userform.get('account_type')?.valueChanges.subscribe((type) => { this.primary_account = type == 'primary'; if (this.primary_account) { this.userform.get('security')?.addValidators([Validators.required]) } else { this.userform.get('security')?.removeValidators([Validators.required]) } this.userform.get('security')?.updateValueAndValidity(); }) } submit() { console.table(this.userform.value) } }
Example output
- When user fill all the required fields and account type is secondary so, we don’t need security code.
2. When user fill all the required fields but account type is primary so, so we need security code also.
3. Finally, When user doesn’t fill any of the required fields.
Hope you find this quick tip useful. See you in the next article.