Skip to content

Instantly share code, notes, and snippets.

@nowsathns
Created March 21, 2019 07:05
Show Gist options
  • Save nowsathns/d8dd998b16109e5d5dce6b6086a65c6d to your computer and use it in GitHub Desktop.
Save nowsathns/d8dd998b16109e5d5dce6b6086a65c6d to your computer and use it in GitHub Desktop.
Custom Date Format Parser for the NGBootstrap DatePicker with Moment.js
import { Component, OnInit } from '@angular/core';
import { FormGroup } from "@angular/forms";
import { FieldConfig } from '../../_models/FieldConfig';
import { NgbDatepickerConfig, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';
import { NgbDateCustomParserFormatter } from '../../_helpers/ngbDateParserFormater';
@Component({
selector: 'app-date',
template: `
<div class="form-group row" [formGroup] = "group">
<label for="field.name" class="col-sm-2">{{ field.label}}</label>
<input type="text" [formControlName]="field.name" ngbDatepicker #d="ngbDatepicker" (focus)="d.open()" class="form-control col-sm-9" [ngClass]="{ 'is-invalid' : isValid() }" (dateSelect) = "OnDateSelect($event)" />
<ng-container *ngFor="let validation of field.validations;">
<div *ngIf="group.controls[field.name].hasError(validation.name) && (group.controls[field.name].dirty || group.controls[field.name].touched)" class="alert alert-danger">
{{ validation.message }}
</div>
</ng-container>
</div>
`,
styles: [],
providers: [NgbDatepickerConfig, {provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter}]
})
export class DateComponent implements OnInit {
field: FieldConfig;
group: FormGroup;
constructor(config: NgbDatepickerConfig) {
}
ngOnInit() {
}
isValid() {
let c = this.group.controls[this.field.name];
return (c.dirty || c.touched) && c.invalid;
}
OnDateSelect($e){
}
}
import { Injectable, Inject } from "@angular/core";
import { NgbDateParserFormatter, NgbDateStruct } from "@ng-bootstrap/ng-bootstrap";
import * as moment from 'moment';
@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
private dformat : string;
constructor(@Inject('dateFormat') df: string) {
super();
//Inject the DateFormat via providers or add a service and get the dateFormat form that
this.dformat = df;
}
parse(value: string): NgbDateStruct {
if (value) {
let d : moment.Moment = moment(value,this.dformat);
console.log(d);
return { year: d.year(), month:(d.month()), day: d.date() };
}
return null;
}
format(date: NgbDateStruct): string {
if(date == null || !date) { return null; }
return moment().year(date.year).month(date.month - 1).date(date.day).format(this.dformat);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment