根据NG-Bootstrap DatePicker 日期模型和格式,
Datepicker 使用 NgbDateStruct 接口作为模型,而不是原生的 Date 对象。
因此,您需要将 Date String 转换为NgbDateStruct
或NgbDate
键入以绑定到[(ngModel)]
.
解决方案 1:将日期字符串转换为NgbDate
或NgbDate
键入。
投射到NgbDate
类型
import { NgbDate } from '@ng-bootstrap/ng-bootstrap';
let date = new Date("2020-10-21T09:39:04.357");
let dateModel: NgbDate = new NgbDate(
date.getFullYear(),
date.getMonth() + 1,
date.getDate())
);
投射到NgbDateStruct
类型
import { NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
let date = new Date("2020-10-21T09:39:04.357");
let dateModel: NgbDateStruct = {
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate()
};
StackBlitz 上的示例解决方案 1
解决方案 2:应用自定义日期适配器
自定义日期适配器允许将日期字符串绑定到[(ngModel)]
自定义日期字符串格式。
日期适配器.ts
import { Injectable } from '@angular/core';
import {
NgbDateAdapter,
NgbDateParserFormatter,
NgbDateStruct
} from '@ng-bootstrap/ng-bootstrap';
/**
* This Service handles how the date is represented in scripts i.e. ngModel.
*/
@Injectable()
export class CustomAdapter extends NgbDateAdapter<string> {
readonly DELIMITER = '-';
fromModel(value: string | null): NgbDateStruct | null {
if (value) {
let date = new Date(value);
return {
day: date.getDate(),
month: date.getMonth() + 1,
year: date.getFullYear()
};
}
return null;
}
toModel(date: NgbDateStruct | null): string | null {
if (date) {
let dateObj = new Date(date.year, date.month - 1, date.day);
return dateObj.toISOString();
}
return null;
}
}
/**
* This Service handles how the date is rendered and parsed from keyboard i.e. in the bound input field.
*/
@Injectable()
export class CustomDateParserFormatter extends NgbDateParserFormatter {
readonly DELIMITER = '/';
parse(value: string): NgbDateStruct | null {
if (value) {
let date = new Date(value);
return {
day: date.getDate(),
month: date.getMonth() + 1,
year: date.getFullYear()
};
}
return null;
}
format(date: NgbDateStruct | null): string {
return date
? date.day + this.DELIMITER + date.month + this.DELIMITER + date.year
: '';
}
}
app.module.ts
import {
NgbDateAdapter,
NgbDateParserFormatter,
NgbModule
} from '@ng-bootstrap/ng-bootstrap';
import { CustomAdapter, CustomDateParserFormatter } from './datepicker-adapter';
@NgModule({
...
providers: [
{ provide: NgbDateAdapter, useClass: CustomAdapter },
{ provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter }
]
})
export class AppModule {}
StackBlitz 上的示例解决方案 2
参考
自定义日期适配器和格式化程序