I am trying to do validation using the <mat-for-field>
and <mat-error>
. This works fine when user tabs out of the input without filling. But how do I force this error to show when I click a button? I am not using submit. Also, using template-driven forms.
This is my code:
HTML:
<mat-form-field>
<input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" required>
<mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>
TS:
dueDateValidator: FormControl = new FormControl('', [Validators.required]);
This works for me. :) On button's click:
Based on Kyle Pfromer's post, I found my solution (to the same problem):
In the TS file I added the StateMatcher after I found an invalid form, eg.
In the MyErrorStateMatcher class I changed as following:
I find it confusing that Angular Material is not detecting the error anyway.
I am providing 3 different solutions for different scenarios, use the one which suits you.
If you are using a form, then do
If you need a particular field to be affected inside form, then filter that nameControl and do
If you are not using forms, then specify a
ref
for theinput
element and initialize variable in ts file & do as follows,Since you want to show mat error on button's click, please try the below: For Angular6 version:
It's important to check how you are using the form control, ".markAsTouched()" on point 3 will show the mat error for the corresponding form control.
You can also easily call the
AbstractControl.updateValueAndValidity()
function on button click. This will run the validation process on the corresponding ForControl again and show errors, if there are some (based on your Validators).So, in your example:
See how to use a form with a custom ErrorStateMatcher
I would make a separate file such as default.error-matcher.ts
Then in the TS file add:
Then change the input to use matcher: