I have two date pickers startDate
and endDate
. I am trying to implement basic date validation where the start date cannot be after the end date.
我需要确保 如果用户选择的结束日期早于开始日期-那么开始日期应更改为所选的结束日期。
I am using (dateChange)
event emitter and it changes the value of startDate
in the model, however, the field value in the actual view does not update until I interact with the startDate
date picker element.
的HTML
<mat-form-field>
<mat-label>Start date</mat-label>
<input matInput [matDatepicker]="fromDate" [value]="startDate"
(dateChange)="changeStartDate($event)" [matDatepickerFilter]="startDateFilter">
<mat-datepicker-toggle matSuffix [for]="fromDate">
<mat-icon matDatepickerToggleIcon>keyboard_arrow_down</mat-icon>
</mat-datepicker-toggle>
<mat-datepicker #fromDate></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>End date</mat-label>
<input matInput [matDatepicker]="toDate" [value]="endDate"
(dateChange)="changeEndDate($event)" [matDatepickerFilter]="endDateFilter">
<mat-datepicker-toggle matSuffix [for]="toDate">
<mat-icon matDatepickerToggleIcon>keyboard_arrow_down</mat-icon>
</mat-datepicker-toggle>
<mat-datepicker #toDate></mat-datepicker>
</mat-form-field>
零件
startDateFilter = (selectedDate: Date | null): boolean => {
return selectedDate < new Date() && selectedDate < this.endDate;
}
endDateFilter = (selectedDate: Date | null): boolean => {
return selectedDate < new Date();
}
changeStartDate(event) {
this.startDate = event.value;
}
changeEndDate(event) {
if (event.value < this.startDate) {
this.startDate.setTime(event.value.getTime());
}
this.endDate = event.value;
}
编辑-变量声明
endDate = new Date();
startDate = new Date(this.endDate.getFullYear(), this.endDate.getMonth(), this.endDate.getDate()-7);
The correction to
startDate
is not picked up immediately by data binding because the bound value, which is the Date object reference, does not change. You can make sure that the change is detected by creating a new Date object:See this stackblitz for a demo.