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

ngx Bootstrap Datepicker如何配置仅允许选择每月首日

解决方案

你需要对现有配置做3处调整即可实现「仅后续每个自然月首日可选中,其余日期全部禁用」的需求:

  • 修正原有配置的语法错误:原dateInputFormat字段引号位置错位,会直接导致代码运行报错
  • 在bsConfig中添加isDisabled自定义禁用规则回调
  • 调整minDate取值,和禁用规则做双重校验,避免异常选中

修改后的完整配置

1. bsConfig 配置

export const bsDatepickerConfig = {
  dateInputFormat: 'DD.MM.YYYY', // 修正原引号错位问题
  containerClass: 'theme-blue',
  showClearButton: true,
  // 新增自定义日期禁用规则
  isDisabled: (date: Date): boolean => {
    // 非每月1号的日期全部禁用
    if (date.getDate() !== 1) {
      return true;
    }
    // 当前自然月及之前月份的1号也禁用,仅保留后续月份首日
    const now = new Date();
    const currentMonthFirstDay = new Date(now.getFullYear(), now.getMonth(), 1);
    return date.getTime() <= currentMonthFirstDay.getTime();
  }
}

2. minDate 配置调整

将原有minDate = new Date()替换为以下配置,直接将最小可选日期设为下个月首日,和禁用规则形成双重保险:

const now = new Date();
// 最小可选日期为下个月1号
minDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);

规则验证

以给出的示例场景(当前日期为2100年7月1日)做校验:

  • 所有非1号日期全部灰化禁用
  • 2100年7月1日属于当前月首日,被禁用
  • 2100年8月1日、9月1日、10月1日、11月1日、12月1日均为可选状态,和需求完全匹配

如果业务使用UTC时间,只需要把回调里的getDate/getMonth/getFullYear替换为getUTCDate/getUTCMonth/getUTCFullYear即可避免时区偏差。
如果需要限制最远可选日期,可自行添加maxDate配置,比如要限制最多选未来1年内的首日,可添加maxDate: new Date(now.getFullYear() + 1, now.getMonth(), 1)到bsConfig中。


内容的提问来源于stack exchange,提问作者Sven Märki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 13:09:12