I have 2 datetime picker, endDate cannot be less than startDate
endDateAfterOrEqualValidator(formGroup): any {
var startDateTimestamp: number;
var endDateTimestamp: number;
startDateTimestamp = Date.parse(formGroup.controls['startDateForm'].value);
endDateTimestamp = Date.parse(formGroup.controls['endDateForm'].value);
return (endDateTimestamp < startDateTimestamp) ? { endDateLessThanStartDate: true } : null;
}
in html:
<mat-form-field>
<input matInput name="endDate" id="endDate" formControlName="endDateForm" [(ngModel)]="endDate" [matDatepicker]="toDatePicker"
placeholder="To Date">
<mat-datepicker-toggle matSuffix [for]="toDatePicker"></mat-datepicker-toggle>
<mat-datepicker disabled="false" #toDatePicker></mat-datepicker>
<mat-error *ngIf="trainingDetail.hasError('endDateLessThanStartDate')">Not valid<mat-error>
</mat-form-field>
with "mat-error", the message does not display. I try to change by "small"
<small *ngIf="trainingDetail.hasError('endDateLessThanStartDate')">Not valid</small>
the message well. Please advice me how to using mat-error
If you want to set a control as invalid from the .ts file manually...
HTML:
TS:
a
mat-error
only shows when a FormControl is invalid, but you have the validation on your formgroup. So in that case you need to use aErrorStateMatcher
In your case it would look like this:
Also worth mentioning, it's not recommended to have two bindings, i.e
formControl
andngModel
. Remove thengModel
and utilize the form control instead. If you receive your start date and end date at a later point, you can usepatchValue
(just set some values to form) orsetValue
(set all values to form)mark in component the errorstatematcher:
As for your custom validator, you don't need to parse the dates, just check if end date is smaller than start date:
and then mark the error state matcher in your template:
Here's a StackBlitz