mat-error 仅适用于控件中的错误,不适用于 formGroup 中的错误。
但在更改您的 dateCheck 以返回具有属性“验证器”而不是“日期”的对象之前
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;
};
}
然后创建一个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));
}
}
并在您的 .ts 中声明
endDateMatcher = new DateEndMatcher();
并在.html中使用
<input matInput [matDatepicker]="picker2" formControlName='end_date'
[errorStateMatcher]="endDateMatcher">
你可以在你的forked stackblitz看到
注意:在新材料角度中,您有一个范围日期选择器
更新还有另一种使用 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;
};
}