I am using the latest Angular Material 5.0.0-rc0
in my Angular 5 app. I am trying to select a range of dates with the datepicker
provided with Angular
It is totally possible to do it but not directly with mat-datepicker component. Actually, mat-datepicker uses mat-menu component to display a mat-calendar component.
To perform what you ask, you could use something like below.
In your component.html file
In your .ts file
isStartDateSelected() {
return (date: Date): MatCalendarCellCssClasses => {
const dateMoment = moment(date);
let startDate;
let endDate;
if (this.startDateAfter) {
startDate = moment(this.startDateAfter);
}
if (this.startDateBefore) {
endDate = moment(this.startDateBefore);
}
if (startDate && endDate && dateMoment.isBetween(startDate, endDate, 'days', '[]')) {
return 'date-selected';
} else if (startDate && dateMoment.isSame(startDate)) {
return 'date-selected';
} else if (moment().startOf('day').isSame(moment(date).startOf('day'))) {
return 'today';
}
return;
};
}
toggleStartDateDate(date: any, calendar: any) {
const dateString = moment(date).format('YYYY-MM-DD');
if (this.selectStartDateType === 'startDateAfter') {
this.startDateAfter = dateString;
this.startDateBefore = dateString;
this.selectStartDateType = 'startDateBefore';
} else {
if (moment(date).isBefore(moment(this.startDateAfter))) {
this.startDateAfter = dateString;
this.startDateBefore = dateString;
this.selectStartDateType = 'startDateBefore';
} else {
this.startDateBefore = dateString;
this.selectStartDateType = 'startDateAfter';
}
}
calendar.updateTodaysDate();
}
In your .css file
::ng-deep .date-selected .mat-calendar-body-cell-content {
background-color: #17a2b8;
color: white;
}
::ng-deep .date-selected.mat-calendar-body-cell:hover .mat-calendar-body-cell-content {
background-color: #17a2b8 !important;
}