I have a requirement that a user can select multiple dates in a date picker. How can I implement multiple date select functionality in an Angular Material date picker?
I tried this through dateClass. But, after every date selection the date picker will be closed.
Here's what I tried
HTML code:
<input matInput [matDatepicker]="picker" placeholder="Choose a date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker [dateClass]="dateClass" #picker></mat-datepicker>
Typescript code:
dateClass = (d: Date) => {
const date = d.getDate();
// Highlight the 1st and 20th day of each month.
return (date === 1 || date === 5 || date === 14 || date === 19 || date === 21 ) ? 'example-custom-date-class' : undefined;
}
One more way (kinda hack): StackBlitz
Just temporary rewriting close method to empty function, and return it back after change. Also calling weekdays rerendering function. Not safe and ideal solution, but works.
Might be useful for somebody.
You need work directly with the mat-calendar, you can enclosed in a mat menu and into a div to avoid "closed", see
I choose store the values of the dates in a string in the way yyyy-MM-dd (*), so
Imports:
TS Code:
Finally the .css is simple:
NOTE: Dont forget to set encapsulation to none in your component:
You can see in stackblitz
(*) you can choose, e.g. store the getTime() of the date selected. The idea is that you need find it in the array "daysSelected", else, if you use directy an object Date, you need compare year, month and day from date to the elements of the array. This give a poor perfomance. Think that the function "isSelected" is called how many times as days has a month, each time a click is done