Angular2 ngbdatepicker how to format date in input field

I am using the bootstrap implementation for angular2 '

ng-bootstrap.imtqy.com

I want to format the date displayed in the input box, which is the model. I looked API did not find any other example, except NgbDateParserFormatter without a special explanation NgbDateParserFormatter

in corner1, it was as simple as adding the attribute format = "MM / dd / yyyy". Can anyone help?

+5
source share
2 answers

I created a problem and found the answer to the following link

https://github.com/ng-bootstrap/ng-bootstrap/issues/1056

+3
source

"By default, the datepicker parameter has a base implementation of this interface that simply accepts dates in ISO format. If you want to process a different format (or several formats) you can provide your own implementation of NgbDateParserFormatter and register it as a provider in your module. Source

https://gist.github.com/nrobinaubertin/61ff1c3db355c74f4e56f485b566ab22 , and here you will find an example implementation.

Copy code from source:

app.component.ts

 import { NgbDatepickerConfig, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap'; import { NgbDateFRParserFormatter } from "./ngb-date-fr-parser-formatter" @Component({ providers: [{provide: NgbDateParserFormatter, useClass: NgbDateFRParserFormatter}] }) export class AppComponent {} 

ngb-date-fr-parser-formatter.ts

 import { Injectable } from "@angular/core"; import { NgbDateParserFormatter, NgbDateStruct } from "@ng-bootstrap/ng-bootstrap"; function padNumber(value: number) { if (isNumber(value)) { return `0${value}`.slice(-2); } else { return ""; } } function isNumber(value: any): boolean { return !isNaN(toInteger(value)); } function toInteger(value: any): number { return parseInt(`${value}`, 10); } @Injectable() export class NgbDateFRParserFormatter extends NgbDateParserFormatter { parse(value: string): NgbDateStruct { if (value) { const dateParts = value.trim().split('/'); if (dateParts.length === 1 && isNumber(dateParts[0])) { return {year: toInteger(dateParts[0]), month: null, day: null}; } else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) { return {year: toInteger(dateParts[1]), month: toInteger(dateParts[0]), day: null}; } else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) { return {year: toInteger(dateParts[2]), month: toInteger(dateParts[1]), day: toInteger(dateParts[0])}; } } return null; } format(date: NgbDateStruct): string { let stringDate: string = ""; if(date) { stringDate += isNumber(date.day) ? padNumber(date.day) + "/" : ""; stringDate += isNumber(date.month) ? padNumber(date.month) + "/" : ""; stringDate += date.year; } return stringDate; } } 
+4
source

Source: https://habr.com/ru/post/1259933/


All Articles