angular - 更改 ngbDatepicker 输入模板
问题描述
我正在开发一个使用此示例的应用程序:
https://stackblitz.com/angular/rynxmynlykl
我想要的是以不同的格式显示选定的日期。而不是yyyy-mm-dd
,我想要mm/dd/yyyy
。占位符很容易更改,但我无法在文档( https://ng-bootstrap.github.io/#/components/datepicker/api)中找到我要查找的内容。
ngModel
接受一个包含年、月和日的对象。然后 Datepicker 将其格式化为上述格式。
我找到的最接近的答案是here,但现在已经过时了(如何更改角度供电引导程序 ngbDatepicker 的模型结构)。
有没有人遇到过这种情况?
解决方案
如DatePicker 文档中所述,您可以提供NgbDateParserFormatter的自定义版本。请参阅此 stackblitz以获取演示。
解析器/格式化程序的以下代码改编自Niels Robin-Aubertin的此 GitHubGist:
import { Injectable } from "@angular/core";
import { NgbDateParserFormatter, NgbDateStruct } from "@ng-bootstrap/ng-bootstrap";
@Injectable()
export class CustomDateParserFormatter extends NgbDateParserFormatter {
parse(value: string): NgbDateStruct {
if (value) {
const dateParts = value.trim().split('/');
if (dateParts.length === 1 && this.isNumber(dateParts[0])) {
return { year: this.toInteger(dateParts[0]), month: null, day: null };
} else if (dateParts.length === 2 && this.isNumber(dateParts[0]) && this.isNumber(dateParts[1])) {
return { year: this.toInteger(dateParts[1]), month: this.toInteger(dateParts[0]), day: null };
} else if (dateParts.length === 3 && this.isNumber(dateParts[0]) && this.isNumber(dateParts[1]) && this.isNumber(dateParts[2])) {
return { year: this.toInteger(dateParts[2]), month: this.toInteger(dateParts[0]), day: this.toInteger(dateParts[1]) };
}
}
return null;
}
format(date: NgbDateStruct): string {
let stringDate: string = "";
if (date) {
stringDate += this.isNumber(date.month) ? this.padNumber(date.month) + "/" : "";
stringDate += this.isNumber(date.day) ? this.padNumber(date.day) + "/" : "";
stringDate += date.year;
}
return stringDate;
}
private padNumber(value: number) {
if (this.isNumber(value)) {
return `0${value}`.slice(-2);
} else {
return "";
}
}
private isNumber(value: any): boolean {
return !isNaN(this.toInteger(value));
}
private toInteger(value: any): number {
return parseInt(`${value}`, 10);
}
}
将日期解析器/格式化程序添加到模块中的提供程序中:
import { NgbDateParserFormatter, ... } from '@ng-bootstrap/ng-bootstrap';
import { CustomDateParserFormatter } from "./datepicker-formatter";
@NgModule({
...
providers: [{ provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter }]
})
export class AppModule { }
推荐阅读
- c++ - 如何计算每个骨骼的起始矩阵(t-pose)(使用 collada 和 opengl)
- javascript - Flask框架,如何使用ajax刷新值
- javascript - Javascript如何对具有相同前缀的逻辑或条件进行分组而不重复它们?
- passwords - ROPC 密码无效
- python - 尝试在 python 上使用 chromedriver.exe 时收到错误消息
- java - Jsh 不断运行命令无休止
- python-3.x - Geopandas 导出更改数据类型
- json - 复制数据活动中的 ADF 合并复制 JSON 文件会为映射数据流创建错误
- r - 基本 dyplr 函数给出错误:“check_dots_used”
- javascript - 清理对象中的 url 而不是单个 url