【问题标题】:How to programmatically change the month in Material Calendar <mat-calendar>如何以编程方式更改 Material Calendar <mat-calendar> 中的月份
【发布时间】:2019-12-25 10:30:32
【问题描述】:

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


    【解决方案1】:

    您可以为此使用_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')
    }
    

    Stackblitz

    【讨论】:

    • 这不公开太奇怪了。
    • @Simon_Weaver 完全同意。我必须深入挖掘才能找到这种方法。像这样的案例很多。记录真的很差
    • @Dino 我正在使用 momen() 作为日期,而您的解决方案对我不起作用。你对此有什么建议吗?
    • @dino 你知道如何用&lt;mat-date-range-picker&gt; 做到这一点吗?使用这个组件时它没有&lt;mat-calendar&gt;?
    【解决方案2】:

    使用[startAt] 自动跳转到最初设置日期的月份。

        <mat-calendar [minDate]="minDate" 
                      [maxDate]="maxDate" 
                      [startAt]="nextShipmentDt$ | async"
                      [selected]="nextShipmentDt$ | async"></mat-calendar>
    

    【讨论】:

    • 此答案不会重置视图类型。 Tnx!
    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      这种使用 Render(角度 10 是 Render2)的解决方法对我有用

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

      【讨论】:

        猜你喜欢
        • 2021-07-13
        • 2020-03-08
        • 1970-01-01
        • 1970-01-01
        • 2020-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多