- 在app.module.ts文件中导入DateAdapter和MAT_DATE_FORMATS,并将其添加到providers中:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule, DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core';
import { AppDateAdapter, CUSTOM_DATE_FORMATS } from './date.adapter';
@NgModule({
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
BrowserAnimationsModule,
MatDatepickerModule,
MatNativeDateModule
],
providers: [
{ provide: DateAdapter, useClass: AppDateAdapter },
{ provide: MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS }
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
- 创建一个自定义日期格式的date.adapter.ts文件:
import { NativeDateAdapter } from '@angular/material/core';
import { MAT_DATE_FORMATS } from '@angular/material/core';
import { Injectable } from '@angular/core';
@Injectable()
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${month}/${day}/${year}`;
} else {
return date.toDateString();
}
}
}
export const CUSTOM_DATE_FORMATS = {
parse: {
dateInput: { month: 'short', year: 'numeric', day: 'numeric' }
},
display: {
dateInput: 'input',
monthYearLabel: { year: 'numeric', month: 'short' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },
monthYearA11yLabel: { year: 'numeric', month: 'long' }
}
};
- 在日期选择器的HTML代码中添加matDatepickerInput和[datepicker]