You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular Material日历中仅启用每月最后一天

实现Angular Material日期选择器仅允许选择每月最后一天

当然可以,matDatepickerFilter支持传入自定义校验函数,完全能实现只允许选择每月最后一天的需求,不用局限于特定日期列表。

具体实现步骤

  1. 在组件类中定义日期过滤函数
    编写一个函数,接收Date类型参数,判断该日期是否为当月最后一天,返回布尔值:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-last-day-picker',
      templateUrl: './last-day-picker.component.html',
      styleUrls: ['./last-day-picker.component.css']
    })
    export class LastDayPickerComponent {
      // 校验日期是否为当月最后一天的过滤函数
      filterLastDayOfMonth = (date: Date): boolean => {
        // 计算当前日期所在月份的下一个月第一天
        const nextMonthFirstDay = new Date(date.getFullYear(), date.getMonth() + 1, 1);
        // 下一个月第一天减去1天,得到当月最后一天
        const lastDayOfMonth = new Date(nextMonthFirstDay.getTime() - 86400000); // 86400000 = 24*60*60*1000(一天的毫秒数)
    
        // 校验传入日期是否等于当月最后一天
        return date.getFullYear() === lastDayOfMonth.getFullYear() &&
               date.getMonth() === lastDayOfMonth.getMonth() &&
               date.getDate() === lastDayOfMonth.getDate();
      };
    }
    
  2. 在模板中绑定过滤函数
    将定义好的函数绑定到matDatepickerFilter属性上:

    <mat-form-field appearance="fill">
      <mat-label>选择每月最后一天</mat-label>
      <input matInput [matDatepicker]="picker" [matDatepickerFilter]="filterLastDayOfMonth">
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>
    

原理说明

matDatepickerFilter的本质是一个动态校验器,它会遍历日期选择器中的每一个日期,将日期传入绑定的函数中:

  • 返回true:该日期允许被选择
  • 返回false:该日期被禁用

上述逻辑通过计算当月最后一天的方式,自动适配所有月份(包括闰年的2月),无需手动维护日期列表。

内容的提问来源于stack exchange,提问作者Abdel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:00:17