Reputation: 205
I've made a datepicker in Angular 8 using the ngbDatepicker from the ng-bootstrap library.
I want to select a whole week by clicking on the weekdays on the left. I know I can select a date and get the week from that but I'm looking for a more elegant solution.
Is this possible in some way?
My Template:
<div id="datepicker-container">
<p>Pick a date:</p>
<!-- Datepicker made using ng bootstrap library
https://ng-bootstrap.github.io/#/components/datepicker/overview -->
<ngb-datepicker
(select)="onDateSelection($event)"
[showWeekNumbers]="true"
[outsideDays]="outsideDays"
[maxDate]="maxDate">
</ngb-datepicker>
</div>
Upvotes: 1
Views: 2140
Reputation: 57941
You can "play" using a day-template. Based on Day template of range selection you can use the styles
.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;
}
And the functions
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);
}
The day template like:
<ng-template #t let-date let-focused="focused">
<span class="custom-day"
[class.focused]="focused"
[class.range]="isRange(date)"
>
{{ date.day }}
</span>
</ng-template>
So, the only thing that you need is, when change select, calculate fromDate and 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())
}
Well, we need other things that is return the week and year when we has the toDate. To this we use this two auxiliar functions
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)
}
We can enclosed all in a custom form control implements our component from ControlValueAccessor, and after calculate the toDate and fromDate call to onChange
see the example in stackblitz
Upvotes: 4