How to add event listener on month change event in an ion-datetime?

Hi,

On ion-datetime, if I change the month using the arrows < or > or if I slide the page to change the month, how can I trigger an event with the month value and the year value that is displayed after month change ?

Many thanks to anyone who can help me.

From the documentation it appears there’s no such feature but I agree it would be very nice to have.

Continuing the discussion from How to add event listener on month change event in an ion-datetime?:

var previous = '';
const targetNode = document.querySelector('ion-datetime#calendar');
const config = { attributes: true, childList: true, subtree: true };
const callback = function(mutationsList, observer) {
    for(const mutation of mutationsList) {
         if (mutation.type === 'attributes') {
            var e = document.querySelector('ion-datetime#calendar').shadowRoot.querySelector('ion-label').textContent;
             if(e !== previous)
             {
                 previous = e;
                 console.log(e);
             }
        }
    }
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
3 Likes

i can help you,

ngAfterViewInit() {
    setTimeout(() => {
      const prevMonthDate: any = () => {
        this.monthStart = format(addMonths(parseISO(this.monthStart), -1), 'yyyy-MM');
        this.monthNext = format(addMonths(parseISO(this.monthNext), -1), 'yyyy-MM');
      };

      const nextMonthDate: any = () => {
        this.monthStart = format(addMonths(parseISO(this.monthStart), 1), 'yyyy-MM');
        this.monthNext = format(addMonths(parseISO(this.monthNext), 1), 'yyyy-MM');
      };

      const calendarHeader = document
        .querySelector('ion-datetime')
        ?.shadowRoot?.querySelector('.calendar-next-prev')
        ?.querySelectorAll('ion-button');
      if (calendarHeader && calendarHeader.length > 1) {
        calendarHeader[0].addEventListener('click', prevMonthDate);
        calendarHeader[1].addEventListener('click', nextMonthDate);
      }
    }, 1000);
  }
1 Like