更改 ngbDatepicker 输入模板

Changing the ngbDatepicker input template

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

https://stackblitz.com/angular/rynxmynlykl

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

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

我找到的最接近的答案在这里,但现在已经过时了 (How to change model structure of angular powered bootstrap ngbDatepicker)。

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

正如 the DatePicker documentation, you can provide a custom version of the NgbDateParserFormatter. See this stackblitz 中提到的演示。

parser/formatter 的以下代码改编自 this GitHubGist by Niels Robin-Aubertin

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);
  }
}

日期parser/formatter添加到模块中的供应商:

import { NgbDateParserFormatter, ... } from '@ng-bootstrap/ng-bootstrap';
import { CustomDateParserFormatter } from "./datepicker-formatter";

@NgModule({
  ...
  providers: [{ provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter }]
})
export class AppModule { }