To create a custom date formatter using ng-bootstrap's NgbDateISOParserFormatter
as inspiration, you can follow the approach below in datepicker-popup.ts
. This code simplifies the formatting process and eliminates the need to import util.ts
:
import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { Injectable } from '@angular/core';
function padNumber(value: number | null) {
if (!isNaN(value) && value !== null) {
return `0${value}`.slice(-2);
} else {
return '';
}
}
@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
parse(value: string): NgbDateStruct | null {
if (value) {
const dateParts = value.trim().split('/');
let dateObj: NgbDateStruct = { day: <any>null, month: <any>null, year: <any>null }
const dateLabels = Object.keys(dateObj);
dateParts.forEach((datePart, idx) => {
dateObj[dateLabels[idx]] = parseInt(datePart, 10) || <any>null;
});
return dateObj;
}
return null;
}
format(date: NgbDateStruct | null): string {
return date ?
`${padNumber(date.day)}/${padNumber(date.month)}/${date.year || ''}` :
'';
}
}
After creating NgbDateCustomParserFormatter
, remember to import it and set the provider in @NgModule
within datepicker-popup.module.ts
:
providers: [
{provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter}
]
I have included this implementation in your StackBlitz project for reference here.