I'm wondering if it is possible to add validation error message (mat-error) for a checkbox for example including the required validation.
<mat-checkbox [formControl]="formControl">
<ng-content></ng-content>
</mat-checkbox>
<mat-error *ngIf="formControl.hasError('required')">
From the docs:
mat-form-field : Error messages can be shown under the form field underline by adding mat-error elements inside the form field.
mat-error cannot be added to a checkbox
Workaround for adding error handling to Checkbox:
<mat-checkbox
formControlName="agreeConditions"
[ngClass]="{'errorCheckbox': checkBoxError}"
>I agree
</mat-checkbox>
<mat-error *ngIf="checkBoxError">
{{errorMessage}}
</mat-error>
You can insert a Function for checkBoxError as well. Change the var "checkBoxError" to a function call getCheckBoxError()
component.ts Function:
getCheckBoxError() {
if(this.formGroup.touched) {
const value = this.formGroup.get('agreeConditions').invalid;
//You can call .hasError('required') as well!
return value;
}
return false;
}
Cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With