Is it correct to implement a custom NgbDateParserFormatter to change the format of the input value on NgbInputDatepicker?

老子叫甜甜 提交于 2019-11-27 17:49:26

As of today implementing a custom NgbDateParserFormatter is the best way to go. So yes, it is a correct way.

In the future we might have a more sophisticated implementation of the NgbDateParserFormatter where you will be able to just pass a desired format (ex. yyyy-MM-dd). Adding this feature will depend on user's interest.

You might also check some more background info in https://github.com/ng-bootstrap/ng-bootstrap/issues/754#issuecomment-247767027

Create custom parser formatter.

import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { Injectable } from '@angular/core';

@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {

  format(date: NgbDateStruct): string {
    return date ? `${isNumber(date.day) ? padNumber(date.day) : ''}-${isNumber(date.month) ? padNumber(date.month) : ''}-${date.year}` : '';
  }
}

Set the provider for the custom parser formatter in the @NgModule.

providers: [
    {provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter}
]

As described in the api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!