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

NgbDatepicker如何实现多选日期并将选中日期存入数组

NgbDatepicker多选功能实现方案

1. 调整TypeScript逻辑

替换原有TS代码为如下内容:

import { NgbDate, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';

// 组件内变量与方法
// 存储选中的多个日期,最终可直接传给后端
selectedDates: NgbDateStruct[] = [];
date: { year: number, month: number };

isDisabled = (date: NgbDateStruct, current: { month: number, year: number }) => {
  return this.disabledDates.find(x => NgbDate.from(x).equals(date)) ? true : false;
}

disabledDates: NgbDateStruct[] = [
  { year: 2021, month: 8, day: 10 },
  { year: 2019, month: 4, day: 12 },
  { year: 2019, month: 4, day: 14 },
]

// 日期选中事件处理
select(date: NgbDateStruct) {
  // 转换为NgbDate对象方便比较
  const target = NgbDate.from(date);
  const existsIndex = this.selectedDates.findIndex(d => NgbDate.from(d).equals(target));
  if (existsIndex > -1) {
    // 已选中则取消选中
    this.selectedDates.splice(existsIndex, 1);
  } else {
    // 未选中则加入选中数组
    this.selectedDates.push(date);
  }
}

// 自定义日期类,用于高亮选中日期
getDayClass = (date: NgbDateStruct) => {
  if (this.selectedDates.find(d => NgbDate.from(d).equals(NgbDate.from(date)))) {
    return 'selected-date';
  }
  return '';
}

2. 修改HTML模板

调整ngb-datepicker标签配置,移除单选绑定的[(ngModel)],新增dayClass属性绑定高亮逻辑:

<ngb-datepicker #dp 
  (navigate)="date = $event.next"
  [markDisabled]="isDisabled" 
  (dateSelect)="select($event)"
  [dayClass]="getDayClass"
></ngb-datepicker>

3. 添加自定义高亮样式

在组件对应的css/scss文件中添加选中日期的样式,可根据需求自定义颜色:

.selected-date {
  background-color: #20c997 !important;
  color: white !important;
  border-radius: 50%;
}

效果说明

点击未选中日期会自动加入selectedDates数组并高亮,点击已选中日期会从数组中移除并取消高亮,最终selectedDates数组就是所有选中的日期集合,可直接传给后端使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:15:02