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]);
the easiest way is call markUserNameTouched() method as below on button click on template. We use markAsTouched() on formControl.
Angular 8 has a new forms method:
markAllAsTouched();
This will mark a control/form and ALL DESCENDANTS as touched!!!
So:
Is the solution.
Either you can do as "Kyle Pfromer" suggested or as you are using form group, you can mark element as touched on submit with