Angular Material mat-calendar设置周一为周起始日求助
解决Angular mat-calendar设置周一为一周起始日的问题
方案一:通过Locale配置(推荐,符合地区习惯)
你当前已设置LOCALE_ID为德语(de),德语区默认周一为一周起始,只需确保mat-calendar的日期适配器读取该Locale配置即可:
- 在AppModule中导入相关依赖:
import { LOCALE_ID, Provider } from '@angular/core'; import { registerLocaleData } from '@angular/common'; import localeDe from '@angular/common/locales/de'; import { DateAdapter, MAT_DATE_LOCALE, NativeDateAdapter } from '@angular/material/core'; registerLocaleData(localeDe);
- 更新
DEV_PROVIDERS配置,关联Locale与日期适配器:
const DEV_PROVIDERS: Provider[] = [ { provide: LOCALE_ID, useValue: "de" }, // 让日期组件复用已配置的LOCALE_ID { provide: MAT_DATE_LOCALE, useExisting: LOCALE_ID }, // 配置NativeDateAdapter使用当前Locale { provide: DateAdapter, useClass: NativeDateAdapter, deps: [MAT_DATE_LOCALE] }, authInterceptorProvider ]; providers: [environment.production ? PROD_PROVIDERS : DEV_PROVIDERS]
方案二:强制自定义周起始(不依赖Locale)
若需跳过Locale限制,直接强制设置周一为一周起始,可自定义日期适配器:
- 创建
custom-date-adapter.ts文件:
import { NativeDateAdapter } from '@angular/material/core'; export class CustomDateAdapter extends NativeDateAdapter { // 1代表周一(0为周日) getFirstDayOfWeek(): number { return 1; } }
- 在AppModule中导入并使用自定义适配器:
import { LOCALE_ID, Provider } from '@angular/core'; import { registerLocaleData } from '@angular/common'; import localeDe from '@angular/common/locales/de'; import { DateAdapter, MAT_DATE_LOCALE } from '@angular/material/core'; import { CustomDateAdapter } from './custom-date-adapter'; // 替换为实际文件路径 registerLocaleData(localeDe); const DEV_PROVIDERS: Provider[] = [ { provide: LOCALE_ID, useValue: "de" }, { provide: MAT_DATE_LOCALE, useExisting: LOCALE_ID }, // 替换为自定义日期适配器 { provide: DateAdapter, useClass: CustomDateAdapter, deps: [MAT_DATE_LOCALE] }, authInterceptorProvider ]; providers: [environment.production ? PROD_PROVIDERS : DEV_PROVIDERS]
模板无需修改
保持原有HTML模板即可:
<mat-calendar [selected]="form.get('businessDate')?.value" (selectedChange)="updateFormDate($event)" [minDate]="prepare?.reservationParameters?.minBusinessDate" [maxDate]="prepare?.reservationParameters?.maxBusinessDate" ></mat-calendar>
内容的提问来源于stack exchange,提问作者Blero Cani
相关产品推荐
相关产品推荐

