djerid
djerid

Reputation: 309

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')">

Upvotes: 5

Views: 11786

Answers (3)

braunpa
braunpa

Reputation: 116

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

Upvotes: 4

Ravid Goldenberg
Ravid Goldenberg

Reputation: 2299

Well a weird work around - I actually needed the form-field-lable but it also works for the mat-error - is using an input of type check-box inside of the form-field while hiding the input that is connected to the form, something like this:

<mat-form-field  appearance="standard">
    <mat-label>check</mat-label>
    <input matInput formControlName="check" [hidden]="true">
    <input (change)="check()" type="checkbox">
    <mat-error>{{ getErrorForCheck() }}</mat-error>
</mat-form-field>

Ya, its ugly, but for keeping my form with labels(or errors) for check-box I use it.

Upvotes: 3

Carsten
Carsten

Reputation: 4208

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

Upvotes: 4

Related Questions