Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set the current view on a mat-calendar (from mat-datepicker) object?

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:

  • calendar.currentView = 'year'
  • calendar._goToDateInView(date,'year')
  • calendar.(yearView and monthView, various things)
like image 984
Gonodactylus Avatar asked Sep 17 '18 13:09

Gonodactylus


1 Answers

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();
like image 94
lukaszwrzaszcz Avatar answered Oct 01 '22 22:10

lukaszwrzaszcz