您可以使用日期模板“玩”。基于范围选择的 Day 模板,您可以使用样式
.custom-day {
text-align: center;
padding: 0.185rem 0.25rem;
display: inline-block;
height: 2rem;
width: 2rem;
}
.custom-day.range{
background-color: rgb(2, 117, 216);
color: white;
}
以及功能
isInside(date: NgbDate) {
return date.after(this.fromDate) && date.before(this.toDate);
}
isRange(date: NgbDate) {
return date.equals(this.fromDate) || date.equals(this.toDate) || this.isInside(date);
}
日模板如:
<ng-template #t let-date let-focused="focused">
<span class="custom-day"
[class.focused]="focused"
[class.range]="isRange(date)"
>
{{ date.day }}
</span>
</ng-template>
所以,您唯一需要的是,当更改选择时,计算 fromDate 和 toDate
onDateSelection(date:NgbDate)
{
let fromDate=new Date(date.year+'-'+date.month+'-'+date.day)
let time=fromDate.getDay()?fromDate.getDay()-1:6
fromDate=new Date(fromDate.getTime()-time*24*60*60*1000)
this.fromDate=new NgbDate(fromDate.getFullYear(),fromDate.getMonth()+1,fromDate.getDate());
const toDate=new Date(fromDate.getTime()+6*24*60*60*1000)
this.toDate=new NgbDate(toDate.getFullYear(),toDate.getMonth()+1,toDate.getDate())
}
好吧,当我们有 toDate 时,我们需要返回星期和年份的其他东西。为此我们使用了这两个辅助函数
calculateWeek(date:any)
{
const time = date.getTime()+4*24*60*60*1000;
const firstDay=new Date(date.getFullYear()+'-1-1')
return Math.floor(Math.round((time - firstDay.getTime()) / 86400000) / 7) + 1;
}
calculateDate(week:number,year:number)
{
const firstDay=new Date(year+'-1-4')
const date=new Date(firstDay.getTime()+(week-1)*7*24*60*60*1000)
const selectDate=new NgbDate(date.getFullYear(),date.getMonth()+1,date.getDate())
this.onDateSelection(selectDate)
}
我们可以将所有的控件封装在一个自定义表单中,从ControlValueAccessor实现我们的组件,并在计算出toDate和fromDate后调用onChange
参见stackblitz中的示例