Angular Material年月选择器如何禁用月份仅支持年份选择
Angular Material 日期选择器仅选年份实现方案
1. 调整HTML模板
修改mat-datepicker的事件绑定,选中年份后直接关闭选择器,避免进入月份选择视图:
<mat-form-field appearance="fill"> <mat-label>选择年份</mat-label> <input matInput [matDatepicker]="dp" [formControl]="date"> <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle> <mat-datepicker #dp startView="multi-year" (yearSelected)="chosenYearHandler($event, dp)" panelClass="year-only-picker"> </mat-datepicker> </mat-form-field>
2. 修改TS逻辑与日期格式
更新自定义日期格式为仅显示年份,调整年份选择处理逻辑,删除无用的月份选择方法:
import {Component} from '@angular/core'; import {FormControl} from '@angular/forms'; import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter'; import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core'; import {MatDatepicker} from '@angular/material/datepicker'; import * as _moment from 'moment'; import {default as _rollupMoment, Moment} from 'moment'; const moment = _rollupMoment || _moment; // 自定义仅年份的日期格式 export const MY_FORMATS = { parse: { dateInput: 'YYYY', }, display: { dateInput: 'YYYY', monthYearLabel: 'YYYY', dateA11yLabel: 'LL', monthYearA11yLabel: 'YYYY', }, }; @Component({ selector: 'datepicker-views-selection-example', templateUrl: 'datepicker-views-selection-example.html', styleUrls: ['datepicker-views-selection-example.css'], providers: [ { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS] }, {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS}, ], }) export class DatepickerViewsSelectionExample { date = new FormControl(moment()); chosenYearHandler(normalizedYear: Moment, datepicker: MatDatepicker<Moment>) { const ctrlValue = this.date.value ?? moment(); // 设置选中的年份,可根据需求默认设置月/日,这里默认设为当年1月1日 ctrlValue.year(normalizedYear.year()); ctrlValue.month(0); ctrlValue.date(1); this.date.setValue(ctrlValue); // 直接关闭选择器,不进入月份选择页 datepicker.close(); } }
3. 可选样式增强
如果需要彻底避免用户误操作进入月份选择页面,可以添加组件样式隐藏月份选择面板:
/* 对应panelClass为year-only-picker的选择器,隐藏月份选择网格 */ .year-only-picker .mat-calendar-body { display: none; } .year-only-picker .mat-calendar-controls { pointer-events: none; }
内容的提问来源于stack exchange,提问作者core114
相关产品推荐
相关产品推荐

