Search code examples
angularangular-materialcalendar

Error when trying to use [dateFilter] and (selectedChange) in mat-calendar, Angular


HTML Code:

<div class="form-group">
                             <mat-calendar (selectedChange)="onSelectCheckInDate($event)"
                                            [selected]="selectedDateForCheckIn"
                                           [minDate]="currentDateAsString">
                                          </mat-calendar>

                             <mat-calendar [selected]="selectedDateForCheckOut"
                                           [minDate]="minDateForCheckout"
                                           (selectedChange)="onSelectCheckOutDate($event)"
                                           [dateFilter]="myFilter"
                             ></mat-calendar>
                            </div>

TS code:

myFilter = (date: Date): boolean => {
    return !this.isDateReserved(date!);
  };

  isDateReserved(date: Date): boolean {
    return this.reservedDates.some(reservedDate => this.isSameDay(date, reservedDate));
  }

  isSameDay(date1: Date, date2: Date): boolean {
    return date1.getFullYear() === date2.getFullYear() &&
      date1.getMonth() === date2.getMonth() &&
      date1.getDate() === date2.getDate();
  }
 onSelectCheckOutDate(event: Event) {
    this.selectedDateForCheckOut = event;
  }

The error is TS2345: Argument of type 'Date | null' is not assignable to parameter of type 'Event_2'. Type 'null' is not assignable to type 'Event_2'.(selectedChange)="onSelectCheckOutDate($event)"

If I delete myFilter method argument (date: Date), the error is gone, but I need that argument. What should I do? Mention that I have the same error if I use dateClass instead of dateFilter.

I tried to implement a mat-calendar, where I need to filter available dates, based on the bookings that are made.


Solution

  • I think your problem is this line:

    onSelectCheckOutDate(event: Event) { this.selectedDateForCheckOut = event; }

    The parameter event is not of type Event. It's a special Angular Material type.

    Try not declaring the type, declaring it as Any, or declaring it as the correct type, from the Material Calendar documentation.