如何设置Angular Material Datepicker仅支持选择年份?
Angular Material DatePicker 仅选择年份配置方案
1. 修改模板代码
在原有模板基础上给mat-datepicker添加yearSelected事件,选中年份后直接关闭选择器,跳过后续月份、日期选择流程,修改后代码如下:
<div class="form-group row"> <label class="col-xl-3 col-lg-3 col-form-label">Production Year</label> <div class="col-lg-9 col-xl-8"> <mat-form-field> <input matInput [matDatepicker]="productionYearPicker" placeholder="Choose a date" formControlName="productionYear" [class.is-invalid]="isControlInvalid('productionYear')" [class.is-valid]="isControlValid('productionYear')"> <mat-datepicker-toggle matSuffix [for]="productionYearPicker"></mat-datepicker-toggle> <mat-datepicker #productionYearPicker startView="multi-year" (yearSelected)="chosenYearHandler($event, productionYearPicker)"> </mat-datepicker> </mat-form-field> </div> </div>
2. 添加组件处理逻辑
在对应的ts组件文件中添加年份选择处理函数,代码如下:
import { MatDatepicker } from '@angular/material/datepicker'; import { FormGroup } from '@angular/forms'; // 你的组件类 export class YourComponent { productionForm: FormGroup; // 替换为你实际的表单变量名 chosenYearHandler(selectedYear: Date, datepicker: MatDatepicker<Date>) { // 可根据业务需要调整赋值逻辑,此处默认赋值为选中年份的1月1日 const targetDate = new Date(selectedYear.getFullYear(), 0, 1); this.productionForm.get('productionYear')?.setValue(targetDate); // 直接关闭选择器,不进入下一级月份选择视图 datepicker.close(); } }
3. 自定义日期显示格式(仅展示年份)
通过配置MAT_DATE_FORMATS修改输入框的日期展示规则,让输入框仅显示年份,不会自动补全月日信息:
方式一:使用原生日期适配器(无需额外依赖)
在组件的providers配置中添加如下代码:
import { MAT_DATE_FORMATS, DateAdapter, NativeDateAdapter } from '@angular/material/core'; // 自定义日期适配器,处理仅年份的解析逻辑 class YearOnlyDateAdapter extends NativeDateAdapter { override format(date: Date, displayFormat: Object): string { if (displayFormat === 'yearOnly') { return date.getFullYear().toString(); } return super.format(date, displayFormat); } } export const YEAR_ONLY_FORMATS = { parse: { dateInput: 'YYYY', }, display: { dateInput: 'yearOnly', monthYearLabel: 'YYYY', dateA11yLabel: 'YYYY', monthYearA11yLabel: 'YYYY', }, }; // 加到组件的@Component装饰器的providers数组中 @Component({ // 其他组件配置 providers: [ { provide: DateAdapter, useClass: YearOnlyDateAdapter }, { provide: MAT_DATE_FORMATS, useValue: YEAR_ONLY_FORMATS } ] })
方式二:使用Moment日期适配器(需提前安装@angular/material-moment-adapter依赖)
import { MAT_DATE_FORMATS, DateAdapter, MAT_DATE_LOCALE } from '@angular/material/core'; import { MomentDateAdapter } from '@angular/material-moment-adapter'; export const YEAR_ONLY_FORMATS = { parse: { dateInput: 'YYYY', }, display: { dateInput: 'YYYY', monthYearLabel: 'YYYY', dateA11yLabel: 'YYYY', monthYearA11yLabel: 'YYYY', }, }; // 加到组件/模块的providers数组中 providers: [ { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }, { provide: MAT_DATE_FORMATS, useValue: YEAR_ONLY_FORMATS } ]
完成以上配置后,日期选择器将仅保留年份选择功能,输入框也只会展示选中的年份数值。
内容的提问来源于stack exchange,提问作者Ke Vin
相关产品推荐
相关产品推荐

