JSPM

  • Created
  • Published
  • Downloads 7396
  • Score
    100M100P100Q130250F

Package Exports

  • angular-mydatepicker

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (angular-mydatepicker) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

angular-mydatepicker

Angular datepicker and date range picker

npm npm

Description

Highly configurable Angular datepicker and date range picker. No dependencies to other libraries.

This project was generated with Angular CLI version 7.3.8. The library is tested with Angular version 7.2.0.

The datepicker source code is in the projects/angular-mydatepicker/src/lib folder.

Online demo is here

Installation

To install this component to an external project, follow the procedure:

  1. npm install angular-mydatepicker --save

  2. Add AngularMyDatePickerModule import to your @NgModule as follows

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { AngularMyDatePickerModule } from 'angular-mydatepicker';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule, ReactiveFormsModule, FormsModule, AngularMyDatePickerModule.forRoot()
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

Usage

Use one of the following two options.

1. ngModel binding

In this option the ngModel binding is used.

To use ngModel define the application class as follows:

import {IAngularMyDpOptions, IMyDateModel} from 'angular-mydatepicker';
// other imports are here...

export class MyTestApp {
  private myOptions: IAngularMyDpOptions = {
    dateRange: false,      // If false = date picker, if true = date range picker
    dateFormat: 'dd.mm.yyyy'
    // other options are here...
  };

  private model: IMyDateModel = null;

  constructor() { }

  // optional date changed callback
  onDateChanged(event: IMyDateModel): void {
    // date selected
  }
}

If you are using bootstrap 4 add the following snippet inside your template:

  • example adds bootstrap input group buttons
<div class="input-group">
  <input class="form-control" placeholder="Select a date" angular-mydatepicker name="mydate"
         [(ngModel)]="model" [options]="myOptions" #dp="angular-mydatepicker" (dateChanged)="onDateChanged($event)"/>
  <div class="input-group-append">
    <button type="button" class="btn btn-secondary" (click)="dp.clearDate()">
      <i class="fa fa-close"></i>
    </button>
  </div>
  <div class="input-group-append">
    <button type="button" class="btn btn-secondary" (click)="dp.toggleCalendar()">
      <i class="fa fa-calendar-o"></i>
    </button>
  </div>
</div>

There are two ways to set an initial date to the model.

  • Initialize with the IMyDate object:
// Initialized to specific date (05.05.2019)
model: IMyDateModel = {isRange: false, singleDate: {date: { year: 2019, month: 5, day: 5 }}};
  • Initialize with the javascript date object:
// Initialized to today
model: IMyDateModel = {isRange: false, singleDate: {jsDate: new Date()}};

2. Reactive forms

In this option the value accessor of reactive forms is used. Here is an example application. It shows how to use the formControlName.

To use reactive forms define the application class as follows:

import {IAngularMyDpOptions, IMyDateModel} from 'angular-mydatepicker';
// other imports are here...

export class MyTestApp implements OnInit {

  myOptions: IAngularMyDpOptions = {
    dateRange: false,      // If false = date picker, if true = date range picker
    dateFormat: 'dd.mm.yyyy'
    // other options...
  };

  private myForm: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    // Initialize to today date
    let model: IMyDateModel = {isRange: false, singleDate: {jsDate: new Date()}, dateRange: null};
    this.myForm = this.formBuilder.group({
      myDate: [model, Validators.required]
      // other controls are here...
    });
  }

  setDate(): void {
    // Set today date using the patchValue function
    let model: IMyDateModel = {isRange: false, singleDate: {jsDate: new Date()}, dateRange: null};
    this.myForm.patchValue({myDate: model);
  }

  clearDate(): void {
    // Clear the date using the patchValue function
    this.myForm.patchValue({myDate: null});
  }
}

Add the following snippet inside your template:

  • Input box styling is bootstrap 4.0.0
<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
    <div class="input-group">
        <input class="form-control" placeholder="Select a date" angular-mydatepicker name="myDate" 
          formControlName="myDate"[options]="myOptions" #dp="angular-mydatepicker"/>
        <div class="input-group-append">
          <button type="button" class="btn btn-secondary" (click)="dp.clearDate()">
            <i class="fa fa-close"></i>
          </button>
        </div>
        <div class="input-group-append">
          <button type="button" class="btn btn-secondary" (click)="dp.toggleCalendar()">
            <i class="fa fa-calendar-o"></i>
          </button>
        </div>
    </div>

    <div class="btnGroup">
        <button class="button" type="submit" [disabled]="myForm.controls.myDate.errors">Submit</button>
        <p class="error" *ngIf="myForm.controls.myDate.errors">Date is required!</p>
    </div>
</form>

Attributes

options attribute

Value of the options attribute is a type of IAngularMyDpOptions. It can contain the following properties.

Option Default Type Description
dateRange false boolean Date picker mode (date picker or date range picker).
dayLabels {su: 'Sun', mo: 'Mon', tu: 'Tue', we: 'Wed', th: 'Thu', fr: 'Fri', sa: 'Sat'} IMyDayLabels Day labels visible on the selector.
monthLabels { 1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec' } IMyMonthLabels Month labels visible on the selector.
dateFormat yyyy-mm-dd string Date format on the selection area and the callback. For example: d.m.yyyy, dd.mm.yyyy, yyyy-m-d, yyyy-mm-dd, d mmm yyyy, dd mmm yyyy (d = Day not leading zero, dd = Day with leading zero, m = Month not leading zero, mm = Month with leading zero, mmm = Month as a text, yyyy = Year four digit)
firstDayOfWeek mo string First day of week on calendar. One of the following: mo, tu, we, th, fr, sa, su
sunHighlight true boolean Sunday red colored on calendar.
satHighlight false boolean Saturday red colored on calendar.
highlightDates no default value Array<IMyDate> Dates red colored on calendar. For example: [{year: 2019, month: 11, day: 14}, {year: 2019, month: 1, day: 15}]
markCurrentDay true boolean Is current day (today) marked (underline) on calendar.
markCurrentMonth true boolean Is current month marked (underline) on calendar. Can be used if monthSelector = true.
markCurrentYear true boolean Is current year marked (underline) on calendar. Can be used if yearSelector = true.
monthSelector true boolean If true and if month label is selected opens a selector of months.
yearSelector true boolean If true and if year label is selected opens a selector of years.
disableHeaderButtons true boolean Prevent to change the calendar view with header buttons if previous or next month are fully disabled by the disableUntil or the disableSince options.
showWeekNumbers false boolean Are week numbers visible or not on calendar. Can be used if firstDayOfWeek = mo.
selectorHeight 232px string Selector height in pixels.
selectorWidth 252px string Selector width in pixels.
disableUntil no default value IMyDate Disable dates backward starting from the given date. For example: {year: 2019, month: 6, day: 26}. To reset the existing disableUntil value set: {year: 0, month: 0, day: 0}
disableSince no default value IMyDate Disable dates forward starting from the given date. For example: {year: 2019, month: 7, day: 22}. To reset the existing disableSince value set: {year: 0, month: 0, day: 0}
disableDates no default value Array<IMyDate> Disable single dates one by one. Array of disabled dates. For example: [{year: 2019, month: 11, day: 14}, {year: 2019, month: 1, day: 15}]. Value of year or month can be zero. If it is zero it affects all years/months. For example disable first day of every month: [{year: 0, month: 0, day: 1}]. To reset existing disableDates value set empty array to it.
disableDateRanges no default value Array<IMyDateRange> Disable date ranges. For example: [{begin: {year: 2019, month: 11, day: 14}, end: {year: 2019, month: 11, day: 20}}]. To reset existing value of disableDateRanges set empty array to it.
disableWeekends false boolean Disable weekends. (Saturday and Sunday).
disableWeekdays no default value Array< string > Disable weekdays. Array of weekdays to disable. Weekdays are same strings as the firstDayOfWeek option. For example: ['tu', 'we'] which disables Tuesdays and Wednesdays.
enableDates no default value Array<IMyDate> Enable single dates one by one if the date is disabled. For example if you disable the date range and want to enable some dates in range. Array of enabled days. For example: [{year: 2019, month: 11, day: 14}, {year: 2019, month: 1, day: 15}]. Value of year or month can be zero. If it is zero it affects all years/months. For example enable first day of every month: [{year: 0, month: 0, day: 1}]. To reset existing enableDates value set empty array to it.
markDates no default value Array<IMyMarkedDates> Mark dates for different colors. For example: [{dates: [{year: 2019, month: 11, day: 14}, {year: 2019, month: 12, day: 16}], color: '#004198'}, {dates: [{year: 2018, month: 10, day: 1}, {year: 2018, month: 11, day: 4}], color: 'green'}]. To reset existing value of markDates set empty array to it.
markWeekends no default value IMyMarkedDate Mark weekends (Saturday and Sunday). For example: {marked: true, color: 'red'}. Value of color can be any CSS color code. To reset existing value of markWeekends set: {marked: false, color: ''}
alignSelectorRight false boolean Align selector right.
openSelectorTopOfInput false boolean Open selector top of input field.
closeSelectorOnDateSelect true boolean Is selector closed or not on a date select.
closeSelectorOnDocumentClick true boolean Is selector closed or not on a document click.
minYear 1000 number Minimum allowed year in calendar. Cannot be less than 1000.
maxYear 9999 number Maximum allowed year in calendar. Cannot be more than 9999.
showSelectorArrow true boolean Is selector (calendar) arrow shown or not.
appendSelectorToBody false boolean Is selector (calendar) appended to body element or not.
focusInputOnDateSelect true boolean Is the input box focused after a date select.
moveFocusByArrowKeys true boolean Is focus moved or not on the calendar by arrow keys.
dateRangeDatesDelimiter " - " string The delimiter of dates in a date range.
inputFieldValidation true boolean Input field validation enabled or not after blur event of input field.
ariaLabelPrevMonth Previous Month string Aria label text of previous month button.
ariaLabelNextMonth Next Month string Aria label text of next month button.

locale attribute

An ISO 639-1 language code can be provided as shorthand for the following options (dayLabels, monthLabels, dateFormat, todayBtnTxt, firstDayOfWeek and sunHighlight). Currently supported languages: en, fr, fr-ch, ja, fi, es, hu, sv, nl, ru, uk, no, tr, pt-br, de, de-ch, it, it-ch, pl, my, sk, sl, zh-cn, he, ro, ca, id, en-au, am-et, cs, el, kk, th, ko-kr, da, lt, vi, bn, bg, hr, ar, is, tw, lv and et.

The locale options can be overridden by options attribute.

  • new locale data can be added to this file. If you want to add a new locale create a pull request.

defaultMonth attribute

Visible month/year when calendar is opened:

  • If date is already selected => calendar opens to the month and year of the selected date
    • In date range mode => calendar opens to the month and year of the selected begin date
  • If the defaultMonth is set => calendar opens to the month and year specified in the the __defaultMonth attribute
  • If none of above => calendar opens to the month and year of current date

Value of the defaultMonth attribute can be:

  • IMyDefaultMonth object. The value of defMonth property can be a string which contain year number and month number separated by delimiter. The delimiter can be any special character. For example: 08-2016 or 08/2016.
  • a string which contain year number and month number separated by delimiter. The delimiter can be any special character. For example: 08-2016 or 08/2016.

Functions

You can can call functions of the directive. Define local variable to input field like below:

<input angular-mydatepicker name="mydate" [(ngModel)]="model" [options]="myOptions" #dp="angular-mydatepicker"/>

The #dp="angular-mydatepicker" defines the local variable named dp. You can use it to call functions of the directive for example (click)="dp.openCalendar()".

openCalendar function

Opens the calendar. For example:

<button type="button" (click)="dp.openCalendar()">Open</button>

closeCalendar function

Closes the calendar. For example:

<button type="button" (click)="dp.closeCalendar()">Close</button>

toggleCalendar function

Closes the calendar if it is open and opens the calendar if it is closed. For example:

<button type="button" (click)="dp.toggleCalendar()">Toggle</button>

clearDate function

Clears the date from the input box and model. For example:

<button type="button" (click)="dp.clearDate()">Clear</button>

isDateValid function

Returns true if the date in the input box is valid. Otherwise it returns false. This function also calls the inputFieldChanged callback.

<input angular-mydatepicker [(ngModel)]="model" [options]="myDatePickerOptions" #dp="angular-mydatepicker"/>
@ViewChild('dp') mdpd: AngularMyDatePickerDirective;

checkDateValidity(): void {
    let valid: boolean = this.mdpd.isDateValid();
    console.log('Valid date in the input box: ', valid);
}

Callbacks

dateChanged callback

  • called when a single date or date range is selected, cleared or input field typing is valid

  • event parameter:

    • event.isRange: true if a date range is selected, false if a single date is selected
    • event.singleDate: event data if isRange is false, if isRange is true this property is null
      • date: IMyDate object for example: { day: 22, month: 11, year: 2019 }
      • jsDate: Javascript Date object
      • formatted: Date string in the same format as the dateFormat option is. For example '2016-11-22'
      • epoc: Epoc time stamp. For example: 1479765600
    • event.dateRange: event data if isRange is true, if isRange is false this property is null
      • beginDate: IMyDate object for example: { day: 22, month: 11, year: 2019 }
      • beginJsDate: Javascript Date object
      • beginEpoc: Epoc time stamp for example: 1479765600
      • endDate: IMyDate object for example: { day: 22, month: 11, year: 2019 }
      • endJsDate: Javascript Date object
      • endEpoc: Epoc time stamp. For example: 1479765600
      • formatted: Date range string. The date is in the same format as the dateFormat option is. For example '2019-11-22 - 2019-11-24'
  • Type of event parameter is IMyDateModel

  • Example of the dateChanged callback:

<input angular-mydatepicker [(ngModel)]="model" [options]="myDatePickerOptions" #dp="angular-mydatepicker" (dateChanged)="onDateChanged($event)"/>
onDateChanged(event: IMyDateModel) {
  console.log('onDateChanged(): ', event);
}

inputFieldChanged callback

  • called when the value change in the input field, date or date range is selected or date is cleared.

  • event parameter:

    • event.value: Value of the input field. For example: '2018-11-22'
    • event.dateFormat: Date format. For example 'yyyy-mm-dd'
    • event.valid: Boolean value indicating is the value of input field valid or not. For example: true
  • Type of event parameter is IMyInputFieldChanged

  • Example of the input field changed callback:

<input angular-mydatepicker [(ngModel)]="model" [options]="myDatePickerOptions" #dp="angular-mydatepicker" (inputFieldChanged)="onInputFieldChanged($event)"/>
onInputFieldChanged(event: IMyInputFieldChanged) {
  console.log('onInputFieldChanged(): Value: ', event);
}

calendarViewChanged callback

  • called when the calendar view change

  • event parameter:

    • event.year: Year number in calendar. For example: 2016
    • event.month: Month number in calendar. For example: 11
    • event.first: First day of selected month and year. Type of IMyWeekday. For example: {number: 1, weekday: "tu"}
    • event.last: Last day of selected month and year. Type of IMyWeekday. For example: {number: 30, weekday: "we"}
  • event parameter type is IMyCalendarViewChanged

  • values of the weekday property are same as values of the firstDayOfWeek option

  • Example of the calendar view changed callback:

<input angular-mydatepicker [(ngModel)]="model" [options]="myDatePickerOptions" #dp="angular-mydatepicker" (calendarViewChanged)="onCalendarViewChanged($event)"/>
onCalendarViewChanged(event: IMyCalendarViewChanged) {
  console.log('onCalendarViewChanged(): Year: ', event);
}

calendarToggle callback

  • called when the calendar is opened or closed

    • event: number from 1 to 4 indicating the reason of the event
      • 1 = calendar opened
      • 2 = calendar closed by date select
      • 3 = calendar closed by calendar button
      • 4 = calendar closed by outside click (document click)
      • 5 = calendar closed by ESC key
  • Example of the calendar toggle callback:

 <input angular-mydatepicker [(ngModel)]="model" [options]="myDatePickerOptions" #dp="angular-mydatepicker" (calendarToggle)="onCalendarToggle($event)"/>
onCalendarToggle(event: number): void {
    console.log('onCalendarClosed(): Reason: ', event);
}

rangeDateSelection callback

  • called in date range mode when a date is selected

    • event parameter:
      • event.isBegin: Is begin date. true if begin date, false if end date
      • event.date: Selected date (IMyDate)
      • event.dateFormat: Date format given in options. For example 'yyyy-mm-dd'
      • event.formatted: Selected date (format based on dateFormat option). For example '2019-05-10'
      • event.epoc: Epoc time stamp. For example: 1557435600
  • Example of the range date selection callback:

 <input angular-mydatepicker [(ngModel)]="model" [options]="myDatePickerOptions" #dp="angular-mydatepicker" (rangeDateSelection)="onDateRangeSelection($event)"/>
onDateRangeSelection(event: IMyRangeDateSelection): void {
  console.log('onDateRangeSelection(): event: ', event);
}

Development of this component

  • At first fork and clone this repo:

    1. git clone https://github.com/kekeh/angular-mydatepicker.git
    2. cd angular-mydatepicker
  • Install tools (version >= 7.3.8):

    1. npm install --g @angular/cli
  • Install dependencies:

    1. npm install
  • Run sample application:

    1. ng serve
    2. Navigate to http://localhost:4200
  • Build datepicker library:

    1. npm run build-lib (dist/angular-mydatepicker folder will be created under the root folder)
  • Build a local npm installation package:

    1. npm run build-lib
    2. cd dist/angular-mydatepicker
    3. npm pack
    • local installation package is created to the dist/angular-mydatepicker folder. For example: angular-mydatepicker-0.0.1.tgz
  • Install local npm package to your project:

    1. npm install path_to_dist/angular-mydatepicker-0.0.1.tgz

Demo

Online demo is here

Compatibility

  • Firefox (version 66.0.3)
  • Chrome (version 72.0.3626.96)
  • Edge - not tested yet
  • IE11 - not tested yet
  • Safari - not tested yet

License

  • License: MIT

Author

  • Author: kekeh

Keywords

  • datepicker
  • date range picker
  • Angular