1 import {Component, Input, forwardRef, OnInit} from '@angular/core';
2 import {NgbDate, NgbCalendar} from '@ng-bootstrap/ng-bootstrap';
3 import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
5 export interface DateRange {
11 selector: 'eg-daterange-select',
12 templateUrl: './daterange-select.component.html',
13 styleUrls: [ './daterange-select.component.css' ],
15 provide: NG_VALUE_ACCESSOR,
16 useExisting: forwardRef(() => DateRangeSelectComponent),
20 export class DateRangeSelectComponent implements ControlValueAccessor, OnInit {
22 // Number of days in the initial
23 // date range shown to user
24 @Input() initialRangeLength = 10;
26 // Start date of the initial
27 // date range shown to user
28 @Input() initialRangeStart = new Date();
32 selectedRange: DateRange;
34 // Function to disable certain dates
35 @Input() markDisabled:
36 (date: NgbDate, current: { year: number; month: number; }) => boolean =
37 (date: NgbDate, current: { year: number; month: number; }) => false
39 onChange = (_: any) => {};
42 constructor(private calendar: NgbCalendar) { }
45 this.selectedRange = {
46 fromDate: new NgbDate(
47 this.initialRangeStart.getFullYear(),
48 this.initialRangeStart.getMonth() + 1,
49 this.initialRangeStart.getDate()),
50 toDate: this.calendar.getNext(
51 this.calendar.getToday(),
53 this.initialRangeLength)
57 onDateSelection(date: NgbDate) {
58 if (!this.selectedRange.fromDate && !this.selectedRange.toDate) {
59 this.selectedRange.fromDate = date;
60 } else if (this.selectedRange.fromDate && !this.selectedRange.toDate && date.after(this.selectedRange.fromDate)) {
61 this.selectedRange.toDate = date;
63 this.selectedRange.toDate = null;
64 this.selectedRange.fromDate = date;
66 this.onChange(this.selectedRange);
69 isHovered(date: NgbDate) {
70 return this.selectedRange.fromDate &&
71 !this.selectedRange.toDate &&
73 date.after(this.selectedRange.fromDate) &&
74 date.before(this.hoveredDate);
77 isInside(date: NgbDate) {
78 return date.after(this.selectedRange.fromDate) && date.before(this.selectedRange.toDate);
81 isRange(date: NgbDate) {
82 return date.equals(this.selectedRange.fromDate) ||
83 date.equals(this.selectedRange.toDate) ||
84 this.isInside(date) ||
88 writeValue(value: DateRange) {
90 this.selectedRange = value;
93 registerOnChange(fn: (value: DateRange) => any): void {
96 registerOnTouched(fn: () => any): void {
100 return this.calendar.getToday();