Background:
By default, the Calendar control will show all dates of the current month, as well as some dates in the previous/next month in order to fill up all 30 date slots in the display. This means that users can select dates from the previous/next month without changing the current month. In some scenarios, developers want to prevent users from being able to select those dates.
Steps to Complete:
1. Set the min and max values of the calendar to be the first and last days of the current month
2. Add the calendar buttons to an array to allow us to tie events to them
3. Use the events tied to the calendar buttons to change the min and max values when the month changes
Getting Started:
Set the min and max values of the calendar to be the first and last days of the current month
In order to set the min and max values, you’ll simply need to pass in a date value to those properties of the calendar control.
HTML:
<wj-calendar :initialized="initCalendar" :min="minDate" :max="maxDate"></wj-calendar>
TypeScript:
minDate = new Date(2020, 1, 1);
maxDate = new Date(2020, 1, 29);
This sets the minimum selectable date to the first of Feb, 2020 and the maximum date to the last of Feb 2020.
Add the calendar buttons to an array to allow us to tie events to them
In the case of the sample, we’re going to be using the getElementsByTagName to return an array of buttons on the page; in this case, we’ll only need 2: the first button of the page, and the third button of the page. These are the ‘Previous Month/Next Month’ buttons that the user will use to navigate the component.
monthButtons: document.getElementsByTagName('button')
initCalendar: function(calendar) {
this.monthButtons[0].addEventListener('click', () => {});
this.monthButtons[2].addEventListener('click', () => {});
}
Use the events tied to the calendar buttons to change the min and max values when the month changes
Now that we have events tied to the buttons for when they get clicked, all we need to do now is modify the min and max value of the component when one of these buttons is clicked, in order to reflect the new month that the user is viewing.
initCalendar: function(calendar) {
this.monthButtons[0].addEventListener('click', () => {
var previousMonth = calendar.min.getMonth() - 1;
if(previousMonth < 0) {
this.currentYear = this.currentYear - 1;
previousMonth = 11;
}
calendar.min = new Date(this.currentYear, previousMonth, 1);
calendar.max = new Date(this.currentYear, previousMonth, this.numberOfDays[previousMonth]);
calendar.displayMonth = calendar.min;
});
this.monthButtons[2].addEventListener('click', () => {
var nextMonth = calendar.min.getMonth() + 1;
if(nextMonth > 11) {
this.currentYear = this.currentYear + 1;
nextMonth = 0;
}
calendar.min = new Date(this.currentYear, nextMonth, 1);
calendar.max = new Date(this.currentYear, nextMonth, this.numberOfDays[nextMonth]);
calendar.displayMonth = calendar.min;
});
}
}
Joel Parks