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

如何在Angular Material Datepicker中禁用周末及特定日期?

在Angular Material Datepicker中禁用周末和特定日期

嘿,我来帮你搞定这个需求!针对你用的Angular 5和对应版本的Angular Material,咱们可以通过matDatepickerFilter这个输入属性轻松实现禁用周末和特定日期的功能,具体步骤如下:

1. 在组件类中定义日期过滤函数

打开你的app.component.ts,添加一个过滤函数和要禁用的特定日期列表:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // 定义需要禁用的特定日期(注意:月份是0-based,比如5代表6月)
  private disabledDates: Date[] = [
    new Date(2024, 5, 15), // 2024年6月15日
    new Date(2024, 5, 20)  // 2024年6月20日
  ];

  // 日期过滤逻辑:返回true表示日期可选,false表示禁用
  dateFilter = (date: Date): boolean => {
    // 禁用周末:周日(0)和周六(6)
    const dayOfWeek = date.getDay();
    const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;

    // 禁用特定日期:比较年、月、日(避免时间部分干扰)
    const isTargetDisabledDate = this.disabledDates.some(disabledDate => {
      return disabledDate.getFullYear() === date.getFullYear() &&
             disabledDate.getMonth() === date.getMonth() &&
             disabledDate.getDate() === date.getDate();
    });

    // 只有非周末且不在禁用列表的日期才可选
    return !isWeekend && !isTargetDisabledDate;
  };
}

2. 在模板中绑定过滤函数

修改你的app.component.html,给input元素添加[matDatepickerFilter]="dateFilter"属性:

<mat-form-field>
  <input matInput 
         [matDatepicker]="picker" 
         [matDatepickerFilter]="dateFilter"
         placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

关键说明

  • matDatepickerFilter是Angular Material Datepicker提供的核心属性,专门用来自定义日期的可选状态。
  • 比较特定日期时,一定要分别对比年、月、日,直接对比Date对象会因为时间戳(时分秒)不同而判断错误。
  • 如果你的禁用日期是从后端接口获取的,只需要在获取数据后更新disabledDates数组即可,过滤函数会自动生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:22:37