无法在NgxDatetimepicker中配置自定义日期格式求助
自定义@angular-material-components/datetime-picker日期格式未生效的原因
你的配置存在两个关键问题导致自定义格式不生效:
1. 日期适配器模块冲突且重复导入
在AppModule的imports数组中:
- 同时导入了
NgxMatNativeDateModule和NgxMatMomentModule,这两个模块均用于提供日期适配器,同时导入会引发适配器优先级冲突,导致自定义格式无法被正确识别。 - 重复导入了
NgxMatMomentModule和NgxMatDatetimePickerModule,虽不会直接报错,但会干扰模块初始化逻辑。
正确做法是仅保留NgxMatMomentModule(你的自定义格式采用moment.js语法,如DD/MM/YYYY HH:mm),移除NgxMatNativeDateModule并删除重复导入项:
const CUSTOM_DATE_FORMATS: NgxMatDateFormats = { parse: { dateInput: 'DD/MM/YYYY HH:mm', }, display: { dateInput: 'DD/MM/YYYY HH:mm', monthYearLabel: "MMM YYYY", dateA11yLabel: "LL", monthYearA11yLabel: "MMMM YYYY" } }; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ReactiveFormsModule, MatInputModule, // ngx NgxMatMomentModule, NgxMatDatetimePickerModule, NgxMatTimepickerModule ], providers:[ { provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS } ], declarations: [AppComponent], bootstrap: [AppComponent], }) export class AppModule {}
2. 未绑定表单控件
HTML中的<input>标签未绑定Angular表单控件(formControl或formControlName),ngx-mat-datetime-picker需通过表单控件传递、格式化日期值,单纯的matInput无法触发格式转换逻辑。
修复步骤:
- 在组件类中定义FormControl:
import { FormControl } from '@angular/forms'; export class AppComponent { dateControl = new FormControl(); }
- 在HTML中绑定控件:
<mat-form-field> <input matInput [formControl]="dateControl" [ngxMatDatetimePicker]="pickerCustomIcon" placeholder="Choose a date"> <ngx-mat-datepicker-toggle matSuffix [for]="pickerCustomIcon"></ngx-mat-datepicker-toggle> <ngx-mat-datetime-picker #pickerCustomIcon [showSeconds]="false"> <ngx-mat-datepicker-actions> <button mat-button ngxMatDatepickerCancel>Cancel</button> <button mat-raised-button color="primary" ngxMatDatepickerApply>Apply</button> </ngx-mat-datepicker-actions> </ngx-mat-datetime-picker> </mat-form-field>
完成以上修改后,自定义的DD/MM/YYYY HH:mm格式即可正常生效。
内容的提问来源于stack exchange,提问作者ruddnisrus
相关产品推荐
相关产品推荐

