Access MatCalendar reference from directive

259 views Asked by At

I have a directive I use for some custom behavior on mat-datepicker.

From within this directive I would like to get access to the associated mat-calendar/MatCalendar component that is opened.

I've tried injecting MatCalendar or using ViewChild to access as in the following code. The result is always null or undefined.

export class DatepickerHelperDirective implements OnInit {
  @ViewChild('mat-calendar', {static: false}) calendar
  @ViewChildren('matCalendar') calendarvc: QueryList<any>
  @Input() pickerEvtDebounceTime: number;
  @Output() keypressDateChange: EventEmitter<moment.Moment> = new EventEmitter();

  private emitSubject = new Subject<moment.Moment>();

  constructor(
    @Optional() private test: MatDatepicker<any>, 
    @Optional() private cal: MatCalendar<any>,
    @Optional() private baseControl: NgControl) {}




<mat-form-field class="date-field mat-input-row col-lg col-md col-sm-12">
  <input
   formControlName="shipDate"
   acsFocus]="jumpFocus === 'shipDate'"
   matDatepicker]="picker"
   matInput
   placeholder="Ship Date"
   acsDatePickerEvtHandler>
   <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
   <mat-datepicker acsDatePickerEvtHandler #picker></mat-datepicker>
</mat-form-field>
1

There are 1 answers

0
cvb On

Unfortunately this doesn't seem like something that will be officially supported by material anytime soon based on this github thread: link

However, this can be done but not in a straightforward way.

You can access the calendar by creating a custom header and using [calendarHeaderComponent] on the <mat-datepicker>. You should be able to successfully inject a MatCalendar into this custom component. Unfortunately you now have to write custom header logic if your users need that!

As an alternative you can also access the MatCalendar by accessing private properties on the MatDatePicker reference: this.pickerRef['_componentRef']['instance']['_calendar']