:)
I'm writing an angular8 web app with angular material.
I use ReactiveForms to build a FormGroup in order to validate it's fields.
I have two fields of To Date and To Time that if I try to submit the form without them being filled, the user sees an error indicating that he needs to fill these values.
below them I have a button called Now that sets the date and time fields well.. to now :)
if I pressed submit first, got the <mat-error> messages below them that they are empty, then pressed the 'Now' button, the fields are being filled but the error messages do not go away. is there a way to re-test specifically these two form fields ?
this is my form with the relevant code of the input elements and the now button:
<form [formGroup]="queryForm" (submit)="runQuery()">
...
<div fxLayout="column wrap">
<div fxLayout="row wrap">
<mat-form-field>
<input matInput #toDate [matDatepicker]="toDatePicker" (focus)="toDatePicker.open()" placeholder="To Date" formControlName="datePeriodTo" />
<mat-datepicker-toggle matSuffix [for]="toDatePicker"></mat-datepicker-toggle>
<mat-datepicker #toDatePicker></mat-datepicker>
<mat-error>{{getError('datePeriodTo')}}</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput #toTime [ngxTimepicker]="toTimePicker" placeholder="To Time" aria-label="To Time" formControlName="timePeriodTo">
<ngx-material-timepicker #toTimePicker></ngx-material-timepicker>
<mat-error>{{getError('timePeriodTo')}}</mat-error>
</mat-form-field>
</div>
<div fxLayout="row wrap" fxLayoutAlign="center">
<button mat-raised-button type="button" (click)="toDate.value=currentDate.format('D/M/YYYY'); toTime.value=currentDate.format('hh:mm a')">Now</button>
</div>
</div>
...
</form>
my getError() function just parses the error and shows the relevant error message:
getError(field: string) {
const control = this.queryForm.get(field);
return control.hasError('required') ? 'field is required' :
control.hasError('greaterThen') ? 'range values not valid' :
control.hasError('lessThen') ? 'range values not valid' :
control.hasError('min') ? 'value is below minimum' :
control.hasError('max') ? 'value is above maximum' :
!control.valid ? 'unknown error' :
'';
}
so in general what I want to happen, that if the are already errors visible for those form fields and I press the Now button so they are filled to current date or time.. to re-check validation and if that's not possible, just to not show these errors because they are not relevant anymore!
I know that i can specifically delete the text in the mat-error fields when I press the Now button but I would assume that angular has a.. more .. a better way to handle it ?
thanks! :)