Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material 2: Add mat-error within a mat-checkbox

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')">
like image 888
djerid Avatar asked Dec 24 '22 07:12

djerid


2 Answers

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

like image 93
Carsten Avatar answered Jan 07 '23 13:01

Carsten


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

like image 39
braunpa Avatar answered Jan 07 '23 13:01

braunpa