Created
November 10, 2017 11:02
-
-
Save lricoy/7d195abf09d10c2ca6acc039f554c2ca to your computer and use it in GitHub Desktop.
Victor date picker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
import { NgbDateStruct, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap'; | |
const now = new Date(); | |
function toInteger(value: any): number { | |
return parseInt(`${value}`, 10); | |
} | |
function isNumber(value: any): value is number { | |
return !isNaN(toInteger(value)); | |
} | |
function padNumber(value: number) { | |
if (isNumber(value)) { | |
return `0${value}`.slice(-2); | |
} else { | |
return ''; | |
} | |
} | |
export class NgbDateVictorParserFormatter 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[0]), month: toInteger(dateParts[1]), day: null}; | |
} else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) { | |
return {year: toInteger(dateParts[0]), month: toInteger(dateParts[1]), day: toInteger(dateParts[2])}; | |
} | |
} | |
return null; | |
} | |
format(date: NgbDateStruct): string { | |
return date ? | |
`${isNumber(date.day) ? padNumber(date.day) : ''}/${isNumber(date.month) ? padNumber(date.month) : ''}/${date.year}` : | |
''; | |
} | |
} | |
@Component({ | |
selector: 'my-app', | |
providers: [{provide: NgbDateParserFormatter, useClass: NgbDateVictorParserFormatter}], | |
template: ` | |
<form class="form-inline"> | |
<div class="form-group"> | |
<div class="input-group"> | |
<input class="form-control" | |
placeholder="yyyy-mm-dd" | |
name="dp" | |
[(ngModel)]="model" | |
ngbDatepicker | |
#d="ngbDatepicker"> | |
<button class="input-group-addon" (click)="d.toggle()" type="button"> | |
x | |
</button> | |
</div> | |
</div> | |
</form> | |
<hr/> | |
<pre>Model: {{ model | json }}</pre> | |
` | |
}) | |
export class AppComponent { | |
model: NgbDateStruct; | |
date: {year: number, month: number}; | |
selectToday() { | |
this.model = {year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate()}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment