如何以编程方式更改材料日历中的月份<mat-calendar>

问题描述 投票:0回答:5

我正在使用带有自定义导航的 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
}

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

javascript angular typescript angular-material
5个回答
20
投票

您可以使用

_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')
}

堆栈闪电战


7
投票

使用
[startAt]
自动跳转到指定月份

    <mat-calendar [minDate]="minDate" 
                  [maxDate]="maxDate" 
                  [startAt]="nextShipmentDt()"
                  [selected]="nextShipmentDt()"></mat-calendar>

4
投票

您也可以尝试以下方法。 (在我检查实现后为我工作 -> MatCalendar)。

this.calendar.activeDate = this.selectedDate; // set the active date to the selected date
this.calendar.updateTodaysDate(); // update calendar state

1
投票

这个使用渲染(角度 10 是 Render2)的解决方法对我有用

https://mariazacharia-k.medium.com/build-a-custom-calendar-with-angular-material-calendar-ebb6806308e5


0
投票

如果您使用 MomentDateAdapter - @Dino 的变体将不起作用:您将在 momentdateadapter.clone 处捕获“date.clone 不是函数”。 您应该使用 MomentDateAdapter 类的 DateAdapter

进口中:

import { MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';

在@Component 提供者中:

providers: [
{provide: DateAdapter, useClass: MomentDateAdapter,deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
]

在变量中:

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

在构造函数中:

    private _adapter: DateAdapter<any>,

功能:

matCalendarOnclickDay(event:Moment): void {
      this.changeDateAngularCalendar(event.toDate());
    }
changeDateMatCalendar(date: Date) {
      let date_ = this._adapter.parse(moment(date).format('YYYY-MM-DD'), 'YYYY-MM-DD');
      this.calendar._goToDateInView(this._adapter.getValidDateOrNull(date_), 'month');
    }

在 HTML 中:

<mat-calendar #calendar 
  [(selected)]="selected" 
  (selectedChange)="matCalendarOnclickDay($event)">
</mat-calendar>
© www.soinside.com 2019 - 2024. All rights reserved.