我有2个日期时间选择器,endDate不能小于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;
}
在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>
如果出现“mat-error”,则不显示该消息 . 我尝试改变“小”
<small *ngIf="trainingDetail.hasError('endDateLessThanStartDate')">Not valid</small>
信息很好 . 请告诉我如何使用mat-error
1 回答
mat-error
仅在 FormControl 无效时显示,但您在表单组上进行了验证 . 那么在这种情况下你需要使用ErrorStateMatcher在你的情况下,它看起来像这样:
另外值得一提的是,不建议使用两个绑定,即
formControl
和ngModel
. 删除ngModel
并改为使用表单控件 . 如果您稍后收到开始日期和结束日期,则可以使用patchValue
(仅设置一些值来形成)或setValue
(将所有值设置为表格)在组件中标记errorstatematcher:
至于您的自定义验证器,您不需要解析日期,只需检查结束日期是否小于开始日期:
然后在模板中标记错误状态匹配器:
这是 StackBlitz