I am unable to properly implement mat-error style change when DatePicker end date input is less than the start date input. The button is able to recognize that the input is invalid by disabling itself, but no error style changes happens on 'end_date'.
Code:
<mat-error *ngIf="userAddressValidations.hasError('validator')">
End date must be greater than start date.
</mat-error>
My goal is to show this error message when the custom validator detects the error.
This is my full sample code:
A mat-error only work for error in controls, not for errors in formGroup.
But before change your dateCheck to return an object with property "validator", not "date"
function dateCheck(): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (
control.value.end_date && //<--check only if has value, not !==undefined
(isNaN(control.value.end_date) ||
control.value.end_date < control.value.start_date)
) {
return { validator: true }; //<--see that it's "validator"
}
return null;
};
}
Then create a customErrorMatcher
export class DateEndMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
//see the comparision
return !!(control && (control.invalid || form.invalid) && (control.dirty || control.touched || isSubmitted));
}
}
And declare in your .ts
endDateMatcher = new DateEndMatcher();
And use in the .html
<input matInput [matDatepicker]="picker2" formControlName='end_date'
[errorStateMatcher]="endDateMatcher">
You can see in your forked stackblitz
NOTE: In the new material angular you has a range date picker
Update there' another approach that it's use SetErrors
function dateCheck(): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (
control.value.end_date &&
(isNaN(control.value.end_date) ||
control.value.end_date < control.value.start_date)
) {
//indicate that setErrors
control.get('end_date').setErrors({validator:true})
return { validator: true };
}
if (control.value.end_date)
control.get('end_date').setErrors(null) //<--put the setErrors to null
return null;
};
}