实现自定义NgbDateParserFormatter以更改NgbInputDatepicker上的输入值的格式是否正确?

Nel*_*eno 47 momentjs ng-bootstrap angular

我在弹出窗口中使用了datepicker(ng-boostrap),我想将日期格式更改为dd-mm-yyyy.

似乎可以通过实现new NgbDateParserFormatter来替换默认值来解决它NgbDateISOParserFormatter.

但我想知道是否还有另一种方式.

更新:

NgbDateParserFormatter使用Moment.js的一个小实现(使用版本1.0.0-alpha.14的ng-bootstrap测试):

import {NgbDateParserFormatter, NgbDateStruct} from '@ng-bootstrap/ng-bootstrap';
import * as moment from 'moment';

export class NgbDateMomentParserFormatter extends NgbDateParserFormatter {
    constructor(private momentFormat: string) {
        super();
    };
    format(date: NgbDateStruct): string {
        if (date === null) {
            return '';
        }
        let d = moment({ year: date.year, 
                         month: date.month - 1, 
                         date: date.day });
        return d.isValid() ? d.format(this.momentFormat) : '';
    }

    parse(value: string): NgbDateStruct {
        if (!value) {
            return null;
        }
        let d = moment(value, this.momentFormat);
        return d.isValid() ? { year: d.year(), 
                               month: d.month() + 1, 
                               day: d.date() } : null;
    }
}
Run Code Online (Sandbox Code Playgroud)

在模块中,您使用工厂包含提供程序以指示日期格式作为参数:

---

@NgModule({

  ---

  providers: [
    { 
      provide: NgbDateParserFormatter, 
      useFactory: () => { return new NgbDateMomentParserFormatter("DD-MM-YYYY") } 
    }
  ]

  ---

})
Run Code Online (Sandbox Code Playgroud)

pko*_*rce 19

截至今天,实施定制NgbDateParserFormatter是最好的方法.是的,这是一种正确的方法.

在未来,我们可能会有一个更复杂的实现NgbDateParserFormatter,您将能够传递所需的格式(例如yyyy-MM-dd).添加此功能取决于用户的兴趣.

您还可以在https://github.com/ng-bootstrap/ng-bootstrap/issues/754#issuecomment-247767027查看更多背景信息.

  • @ pkozlowski.opensource如果我们使用AOT编译,如何更改这个答案?我试过`export function NgbDateMomentParserFormatterFactory(){return new NgbDateMomentParserFormatter("DD-MM-YYYY"); }`和`providers:[{provide:NgbDateParserFormatter,useFactory:NgbDateMomentParserFormatterFactory}]`但是这似乎没有应用这些更改. (3认同)
  • 使用AOT编译器时请勿使用工厂.试试这个例子:https://gist.github.com/nrobinaubertin/61ff1c3db355c74f4e56f485b566ab22 (2认同)