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

如何自定义Angular Material的mat calendar日历头部,实现截图所示效果

mat-calendar 自定义头部实现指南

实现效果如下:
自定义日历头部效果示例

核心实现步骤

  • 第一步:创建自定义头部组件
    执行CLI命令生成组件:
    ng g c custom-calendar-header
  • 第二步:编写自定义头部组件逻辑
    组件HTML示例:
    <div class="custom-calendar-header">
      <button mat-icon-button (click)="prevMonth()">
        <mat-icon>chevron_left</mat-icon>
      </button>
      <div class="header-date">
        <span class="year">{{activeDate.getFullYear()}}</span>
        <span class="month">{{monthNames[activeDate.getMonth()]}}</span>
      </div>
      <button mat-icon-button (click)="nextMonth()">
        <mat-icon>chevron_right</mat-icon>
      </button>
    </div>
    
    组件TS核心逻辑:
    import { Component, Inject } from '@angular/core';
    import { MAT_CALENDAR_HEADER, MatCalendarHeader } from '@angular/material/datepicker';
    import { DateAdapter } from '@angular/material/core';
    
    @Component({
      selector: 'app-custom-calendar-header',
      templateUrl: './custom-calendar-header.component.html',
      styleUrls: ['./custom-calendar-header.component.scss']
    })
    export class CustomCalendarHeaderComponent extends MatCalendarHeader<Date> {
      monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
    
      constructor(
        @Inject(MAT_CALENDAR_HEADER) public data: any,
        private dateAdapter: DateAdapter<Date>
      ) {
        super(data);
      }
    
      prevMonth() {
        const prevMonth = this.dateAdapter.addMonths(this.activeDate, -1);
        this.activeDate = prevMonth;
      }
    
      nextMonth() {
        const nextMonth = this.dateAdapter.addMonths(this.activeDate, 1);
        this.activeDate = nextMonth;
      }
    }
    
  • 第三步:在父组件中绑定自定义头部
    父组件HTML配置:
    <mat-calendar 
      [headerComponent]="customHeader" 
      [(selected)]="selectedDate"
    >
    </mat-calendar>
    
    父组件TS声明:
    import { CustomCalendarHeaderComponent } from './custom-calendar-header/custom-calendar-header.component';
    
    // 类内部声明
    customHeader = CustomCalendarHeaderComponent;
    selectedDate = new Date();
    
  • 第四步:调整样式匹配设计
    通过样式覆盖调整头部排版与示例效果一致,示例样式:
    .custom-calendar-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 16px;
      .header-date {
        display: flex;
        gap: 8px;
        font-size: 18px;
        font-weight: 500;
      }
    }
    // 覆盖mat-calendar默认头部边距
    ::ng-deep .mat-calendar-header {
      padding: 0 !important;
    }
    

注意事项

  • 需在对应模块的declarations数组中添加CustomCalendarHeaderComponent声明
  • 如需支持年/月快速选择,可在头部添加下拉组件直接绑定activeDate属性即可
  • 多语言场景可直接通过DateAdapter获取格式化后的年月文本,无需手动维护月份名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:27:04