Example 1: Conditional Required Validator
Require a reason input and an email input only when the "Sorry" option is selected. The required validator is applied to the text input control only when the "Sorry" option is chosen.
import {ifValidator} from 'ngx-lift';
import {Component} from '@angular/core';
import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
@Component({
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<clr-radio-container>
<label>Do you like this tool?</label>
<clr-radio-wrapper>
<input type="radio" clrRadio name="choice" value="LIKE" [formControl]="form.controls.choice" (change)="changeChoice()" />
<label>Of course 😜</label>
</clr-radio-wrapper>
<clr-radio-wrapper>
<input type="radio" clrRadio name="choice" value="UNLIKE" [formControl]="form.controls.choice" (change)="changeChoice()" />
<label>Sorry 😅</label>
</clr-radio-wrapper>
</clr-radio-container>
<clr-input-container>
<label>Email</label>
<input clrInput type="text" [formControl]="form.controls.email" />
<clr-control-error *clrIfError="'required'">Required</clr-control-error>
<clr-control-error *clrIfError="'email'">Invalid email</clr-control-error>
</clr-input-container>
<clr-input-container>
<label>Reason why you don't like</label>
<input clrInput type="text" [formControl]="form.controls.reason" />
<clr-control-error *clrIfError="'required'">Required</clr-control-error>
</clr-input-container>
</form>
`
})
export class IfValidatorComponent {
validator = ifValidator(
() => this.form?.controls.choice.value === 'UNLIKE',
[Validators.required],
// add mismatch validation functions if needed
);
form = new FormGroup({
choice: new FormControl('', Validators.required),
email: new FormControl('', [this.validator, Validators.email]),
reason: new FormControl('', this.validator),
});
// updateValueAndValidity whenever the condition is changed.
changeChoice() {
this.form.controls.email.updateValueAndValidity();
this.form.controls.reason.updateValueAndValidity();
}
}updateValueAndValidity() method on the associated control whenever there is a change in the specified condition for either ifValidator or ifAsyncValidator.