首页 > 解决方案 > 如何以编程方式更改材料日历中的月份

问题描述

我正在使用带有自定义导航的 Material Calendar 组件,该导航显示您在日历中选择日期后接下来的 5 天。

当您在自定义元素中选择一个日期时,它会使用新选择的日期更新日历,但如果传入日期在下个月,我希望日历自动切换到该月。

HTML:

<mat-calendar [selected]="selectedDate" (selectedChange)="onDateSelected($event)"
  [minDate]="minDate" [dateClass]="dateClass"></mat-calendar>

TS:

@Input() set incomingDate(d: Date) {
    this.selectedDate = d; // sets the incoming date on mat-calendar
    this.dateClass(d); // highlights the next 5 days in the mat-calendar
    this.calendar.updateTodaysDate(); // re-renders calendar to see changes
}

有什么方法可以绑定到元素来解决这个问题吗?谢谢!

标签: javascriptangulartypescriptangular-material

解决方案


你可以使用_goToDateInView它。它不会更改日期对象,它只会转到您作为参数传递的月份,因此您可以保持日期选择逻辑不变。

/** Handles year/month selection in the multi-year/year views. */
_goToDateInView(date: D, view: 'month' | 'year' | 'multi-year'): void;

这里是你如何使用它:

模板

<mat-calendar #calendar></mat-calendar>

零件

@ViewChild('calendar', {static: false}) calendar: MatCalendar<Date>;

public goToDate() {
   this.calendar._goToDateInView(someDateObjectInAnotherMonth, 'month')
}

堆栈闪电战


推荐阅读