首页 > 解决方案 > 更改 ngbDatepicker 输入模板

问题描述

我正在开发一个使用此示例的应用程序:

https://stackblitz.com/angular/rynxmynlykl

我想要的是以不同的格式显示选定的日期。而不是yyyy-mm-dd,我想要mm/dd/yyyy占位符很容易更改,但我无法在文档( https://ng-bootstrap.github.io/#/components/datepicker/api)中找到我要查找的内容。

ngModel接受一个包含年、月和日的对象。然后 Datepicker 将其格式化为上述格式。

我找到的最接近的答案是here,但现在已经过时了(如何更改角度供电引导程序 ngbDatepicker 的模型结构)。

有没有人遇到过这种情况?

标签: angularng-bootstrap

解决方案


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 { }

推荐阅读