Reputation: 121
I'm trying to make a 'persistent' month/year picker using angular material2- the catch is that I don't want a traditional datepicker, but just the calendar part, which will remain open at all times and display the chosen month. I have the functionality more or less working, but the problem is that once you've chosen the month, the 'smart' calendar automatically changes the view to the day picker.
Current code:
HTML
<mat-calendar #monthPicker
startView="year"
(yearSelected)="yearChosen($event, date)"
(monthSelected)="monthChosen($event, date, monthPicker)"
[selected]="date"
></mat-calendar>
TS (relevant portions)
yearChosen(year : Date, date : Date){
//(date is a reference to a class-level date variable, just holds the current value)
date.setFullYear(year.getFullYear())
}
monthChosen(month: Date, dateObj : Date, calendar : MatCalendar<Date>){
date.setMonth(month.getMonth());
//SOME CODE TO MAKE CALENDAR NOT PROCEED TO THE DAY VIEW???
}
I've tried messing with the objects on the datepicker object, but nothing seems to have any effect:
Upvotes: 7
Views: 13024
Reputation: 38
Just to improve @lukaszwrzaszcz answer.
You can change month programatically and refresh datepicker:
ngOnChanges(changes) {
if (changes.viewDate && changes.viewDate.previousValue) {
if (!dayjs(changes.viewDate.currentValue).isSame(dayjs(changes.viewDate.previousValue), 'month')) {
this.selectedMonth.setMonth(changes.viewDate.currentValue.getMonth());
this.matCalendar.updateTodaysDate();
}
}
}
Upvotes: 0
Reputation: 170
You can use startAt property:
<mat-calendar class="month-calendar" [startAt]="selectedMonth"></mat-calendar>
Bind startAt with the Date object in component:
selectedMonth: Date;
Inject calendar component reference:
@ViewChild(MatCalendar, {static: false}) calendar: MatCalendar<Date>;
Then you can change month programatically and refresh datepicker:
this.selectedMonth.setMonth(this.selectedMonth.getMonth() + 1);
this.calendar.updateTodaysDate();
Upvotes: 7