I'm using angular 7 and I have a form with two input fields, while the first one is always required, the second one should be required only if a checkbox is checked.
I'm trying to use a FormGroup with a custom validator:
exampleForm: FormGroup;
checked: boolean;
ngOnInit() {
this.exampleForm = new FormGroup({
'second': new FormControl('', [this.validateIfChecked()]),
'first': new FormControl('example', [Validators.required])
});
}
validateIfChecked(): ValidatorFn {
return (control: AbstractControl): {
[key: string]: any
} | null => {
if (this.checked) {
return control.value ? null : {
'err': true
};
}
return null;
}
}
The problem is that the validation is performed only when the text in the two input fields is updated, while if I check/uncheck the checkbox the state doesn't change and to force the validation I have to change the text in the second textbox.
Here you can see an example on stackblitz: if you check the checkbox, the status doesn't change.
How can can I force the validation when the checkbox status changes?
You can dynamically add validation required to the form control based on checkbox clicked.
Template:
<form [formGroup]="exampleForm">
<mat-form-field>
<input matInput placeholder="first" formControlName="first">
</mat-form-field>
<mat-checkbox [(ngModel)]="checked" [ngModelOptions]="{standalone:true}" (click)="checkstate()">Make second input field required</mat-checkbox>
<mat-form-field>
<input matInput placeholder="second" formControlName="second">
</mat-form-field>
</form>
Component:
checkstate(){
this.checked = !this.checked;
if(this.checked){
this.exampleForm.get('second').setValidators(Validators.required);
}else{
this.exampleForm.get('second').clearValidators();
}
this.exampleForm.get('second').updateValueAndValidity();
}