使用 ng-bootstrapNgbDateISOParserFormatter
作为指南,在datepicker-popup.ts
. 下面的代码(IMO)比原始代码更简单,并且不依赖于导入util.ts
:
import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { Injectable } from '@angular/core';
function padNumber(value: number | null) {
if (!isNaN(value) && value !== null) {
return `0${value}`.slice(-2);
} else {
return '';
}
}
@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
parse(value: string): NgbDateStruct | null {
if (value) {
const dateParts = value.trim().split('/');
let dateObj: NgbDateStruct = { day: <any>null, month: <any>null, year: <any>null }
const dateLabels = Object.keys(dateObj);
dateParts.forEach((datePart, idx) => {
dateObj[dateLabels[idx]] = parseInt(datePart, 10) || <any>null;
});
return dateObj;
}
return null;
}
format(date: NgbDateStruct | null): string {
return date ?
`${padNumber(date.day)}/${padNumber(date.month)}/${date.year || ''}` :
'';
}
}
然后在in 中导入NgbDateCustomParserFormatter
并设置提供程序:@NgModule
datepicker-popup.module.ts
providers: [
{provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter}
]
我已经分叉了您的 StackBlitz 并在此处添加了此功能。