Search code examples
angulartypescriptdatetimeionic-frameworkcalendar

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


When the user changes the month i need to re-render the highlightedDates: a query is called and retrieve all the dates of that month. It works if the user use the top button to manually select a month and the year, but if he just click on the arrows: "<" ">" then the ionChange is not trigger.

  <div class="calendar">
    <ion-datetime
      [(ngModel)]="selectedDate"
      presentation="date"
      locale="it-IT"
      [highlightedDates]="allAppointments"
      (ionChange)="createAppointmentList()"
    >
    </ion-datetime>

Basically i need an eventListener when the user click on the arrows of the calendar


Solution

  • Somewhat found a solution thanks to Misha Mashina comment

      initMonthObserver(){
        const monthText = document.querySelector('ion-datetime')?.shadowRoot?.querySelector('.calendar-header')?.querySelector('ion-label');
        const elementToObserve = document.querySelector('ion-datetime')?.shadowRoot?.querySelector('.calendar-body')
    
        if (elementToObserve) { 
          const observer = new MutationObserver((mutationsList, observer) => {
    
            this.monthString = monthText?.textContent;
            let parts = this.monthString.split(" ")
            let monthIndex = this.monthNames.indexOf(parts[0].toLowerCase())
            let monthNumber = monthIndex + 1
            let year = parts[1]
    
            if(this.monthString){
              this.monthToDate = new Date(year, monthNumber).toISOString()
              this.queryAppsPerMonth(this.monthToDate)
            }
    
          })
          const observerConfig = {
            childList: true, 
            subtree: true, 
          };
          observer.observe(elementToObserve, observerConfig)
        }
      }
    

    Got the calendar element using:

     document.querySelector('ion-datetime')?.shadowRoot?.querySelector('.calendar-body')
    

    Then MutationObserver to track mutation of that