1、官方示例nz-date-picker
官方示例中做到的效果無法滿足業務查詢的務求,比如:我需要先選中開始時間,然后再選擇結束時間時無法選中相同日期的數據,並且即使選擇“此刻”時,對應的時間也沒有進行禁用
說明:ng-zerro是有對應的實現的,但是在示例中相對簡單,無法達到效果,本文僅僅做了自己的實現記錄
2、如何實現可以選擇相同的時間,並且禁用不在選中時間范圍內的時間
如:開始時間2020-11-09 12:12:12,結束時間需要選中2020-11-09 12:12:12,並且小於2020-11-09 12:12:12的時間需要禁用
html實現:
<nz-date-picker
[nzDisabledTime]="disabledStartTime"
[nzDisabledDate]="disabledStartDate"
nzShowTime
nzFormat="yyyy-MM-dd HH:mm:ss"
[(ngModel)]="startValue"
nzPlaceHolder="開始時間"
(ngModelChange)="onStartChange($event)"
>
</nz-date-picker>
<nz-date-picker
[nzDisabledTime]="disabledEndTime"
[nzDisabledDate]="disabledEndDate"
nzShowTime
nzFormat="yyyy-MM-dd HH:mm:ss"
[(ngModel)]="endValue"
nzPlaceHolder="結束時間"
(ngModelChange)="onEndChange($event)"
>
</nz-date-picker>
ts實現:
// 對日期進行配置
disabledStartDate = (startValue: Date): boolean => {
if (!startValue || !this.endValue) {
return false;
}
// 相同時間可以選擇
if (startValue.getTime() === this.endValue.getTime()){
return false;
}
return startValue.getTime() >= this.endValue.getTime();
}
disabledEndDate = (endValue: Date): boolean => {
if (!endValue || !this.startValue) {
return false;
}
if (endValue.getDate() === this.startValue.getDate()) {
// 相同日期不禁用
return false;
}else{
// 相同時間可以選擇
return endValue.getTime() <= this.startValue.getTime();
}
}
// 對時間進行禁用
disabledStartTime: DisabledTimeFn = (_value: Date, type?: DisabledTimePartial) => {
// 對開始時間進行設置
if (!this.endValue){
return null;
}
if (!_value){
_value = this.endValue;
}
let disableMinutes = [];
let disableSeconds = [];
if (_value.getHours() < this.endValue.getHours()){
disableMinutes = [];
disableSeconds = [];
}else{
disableMinutes = this.range(this.endValue.getMinutes() + 1, 60);
if (_value.getMinutes() < this.endValue.getMinutes()){
disableSeconds = [];
}else{
disableSeconds = this.range(this.endValue.getSeconds() + 1, 60);
}
}
return {
nzDisabledHours: () => this.range(this.endValue.getHours() + 1, 24),
nzDisabledMinutes: () => disableMinutes,
nzDisabledSeconds: () => disableSeconds
};
}
disabledEndTime: DisabledTimeFn = (_value: Date, type?: DisabledTimePartial) => {
// 對結束時間進行設置
if (!this.startValue){
return null;
}
if (!_value){
_value = this.startValue;
}
let disableMinutes = [];
let disableSeconds = [];
if (_value.getHours() > this.startValue.getHours()){
disableMinutes = [];
disableSeconds = [];
}else{
disableMinutes = this.range(0, this.startValue.getMinutes());
if (_value.getMinutes() > this.startValue.getMinutes()){
disableSeconds = [];
}else{
disableSeconds = this.range(0, this.startValue.getSeconds());
}
}
return {
nzDisabledHours: () => this.range(0, this.startValue.getHours()),
nzDisabledMinutes: () => disableMinutes,
nzDisabledSeconds: () => disableSeconds
};
}
3、效果:
3.1、有開始時間,選擇結束時間:
3.2、有結束時間,選擇開始時間:
個人博客 蝸牛