Search code examples
angularangular-materialmat-datepicker

How to add close button to customized mat-datepicker-header


I am using this UI component from the Angular material.

https://material.angular.io/components/datepicker/overview#customizing-the-calendar-header

I want to add close button the custom header but it seems not possible yet.

At least I would like to get output event from the date picker header component.


Solution

  • As the MatDatepicker and MatCalendarHeader are two separate components, you will need to pass data between the components using an EventEmitter, or with BehaviourSubject through the use of a service.

    For this example, I will make use of a service. First, you may create a service called calendar-service.ts, which will be used to share data between components. Within this class, we will make use of BehaviourSubject to emit the updated boolean value which will denote if the datepicker should be open or close.

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable()
    export class CalendarService {
    
      closeCalendarSource = new BehaviorSubject<boolean>(false);
      isCloseCalander = this.closeCalendarSource.asObservable();
    
      constructor() { }
    
      closeCalander(message: boolean) {
        this.closeCalendarSource.next(message)
      }
    
    }
    

    On the template for your MatCalendarHeader, you should add a button which is binded to the click event, which will trigger the action to close the datepicker

    <button mat-icon-button (click)="closeCalendar()" >
      <mat-icon>close</mat-icon>
    </button>
    

    And on the component.ts for the header,

    constructor(
      private calendarService: CalendarService) {
    }
    
    closeCalendar() {
      this.calendarService.closeCalander(true);
    }
    

    On the main component that uses the MatDatepicker, you will subscribe to the observable which will emit the current value from the header component.

    @ViewChild('picker', { static: false}) picker;
    exampleHeader = ExampleHeader;
    
    constructor(private calendarService: CalendarService) {}
    
    ngOnInit() {
      this.calendarService.isCloseCalander.subscribe(isClose => {
        if (isClose) {
          this.picker.close();
        }
      });
    }
    

    I have created the full demo over here.