Skip to content

Instantly share code, notes, and snippets.

@Banttu
Created July 18, 2017 18:19
Show Gist options
  • Save Banttu/8dc8617659818cd5a80f8b64b9df1bf7 to your computer and use it in GitHub Desktop.
Save Banttu/8dc8617659818cd5a80f8b64b9df1bf7 to your computer and use it in GitHub Desktop.
Flatpickr component for use with Angular
<button (click)="toggle()">Date</button>
<div [hidden]="!visible">
<div #flatpickr></div>
</div>
@import '~flatpickr/dist/flatpickr.min.css';
import { Component, Output, EventEmitter, OnInit, ElementRef, ViewChild } from '@angular/core';
import * as flatpickr from 'flatpickr';
import * as moment from 'moment/moment';
export interface DateRange {
startDate: string;
endDate: string;
}
@Component({
selector: 'app-flatpickr',
templateUrl: './flatpickr.component.html',
styleUrls: ['./flatpickr.component.scss']
})
export class FlatpickrComponent implements OnInit {
@ViewChild('flatpickr') el: ElementRef;
@Output() dateChanged: EventEmitter<DateRange> = new EventEmitter();
visible: boolean = false;
dates: DateRange;
ngOnInit() {
flatpickr(this.el.nativeElement, {
inline: true,
enableTime: true,
time_24hr: true,
minuteIncrement: 1,
mode: 'range',
locale: {
firstDayOfWeek: 1
},
onChange: (val) => this.handleChange
});
}
toggle() {
this.visible = !this.visible;
if (!this.visible) {
this.dateChanged.emit(this.dates);
}
}
handleChange(val: Date[]) {
if (val.length === 1) {
this.dates = {
startDate: moment(val[0]).utc(false).toISOString(),
endDate: null
};
return;
}
if (val.length === 2) {
this.dates = {
startDate: moment(val[0]).utc(false).toISOString(),
endDate: moment(val[1]).utc(false).toISOString()
};
}
}
}
Copy link

ghost commented Jul 18, 2017

thanks dude

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment