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

如何基于Angular Material实现多选日历功能?

实现Angular Material日历多选日期

Angular Material原生的mat-calendar组件没有内置多选日期功能,我们可以通过自定义逻辑实现,核心思路是维护一个选中日期数组,通过dateClass标记选中状态,并处理日期点击事件来切换选中状态。

改造后的组件代码

TypeScript 代码

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

@Component({
  selector: 'datepicker-inline-calendar-example',
  templateUrl: 'datepicker-inline-calendar-example.html',
  styleUrls: ['datepicker-inline-calendar-example.css'],
})
export class DatepickerInlineCalendarExample {
  // 存储选中的日期数组
  selectedDates: Date[] = [];

  constructor(private dateAdapter: DateAdapter<Date>) {}

  // 自定义日期类,标记选中的日期
  dateClass = (date: Date): string => {
    const isSelected = this.selectedDates.some(selectedDate => 
      this.dateAdapter.sameDate(selectedDate, date)
    );
    return isSelected ? 'selected-date' : '';
  };

  // 处理日期点击事件,切换选中状态
  handleDateSelection(date: Date): void {
    const existingIndex = this.selectedDates.findIndex(selectedDate => 
      this.dateAdapter.sameDate(selectedDate, date)
    );

    if (existingIndex > -1) {
      // 已选中,移除该日期
      this.selectedDates.splice(existingIndex, 1);
    } else {
      // 未选中,添加该日期
      this.selectedDates.push(date);
    }
  }
}

HTML 代码

<mat-card class="demo-inline-calendar-card">
  <!-- 绑定日期选中事件和自定义日期类 -->
  <mat-calendar 
    (selectedChange)="handleDateSelection($event)"
    [dateClass]="dateClass">
  </mat-calendar>
</mat-card>

<!-- 显示选中的日期 -->
<p>选中的日期:</p>
<ul>
  <li *ngFor="let date of selectedDates">{{ date | date:'yyyy-MM-dd' }}</li>
</ul>

样式代码(可选,用于高亮选中日期)

.selected-date {
  background-color: rgba(63, 81, 181, 0.2);
  border-radius: 50%;
}

.selected-date .mat-calendar-body-cell-content {
  color: #3f51b5;
  font-weight: bold;
}

关键说明

  • 使用DateAdapter的sameDate方法准确比较日期,避免因时间部分不同导致判断错误
  • 通过dateClass输入属性为选中日期添加自定义样式
  • 在selectedChange事件中处理日期的添加/移除逻辑,维护选中日期数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:10:28