6.3.6 • Published 9 months ago

ng2-daterangepicker-material-2 v6.3.6

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

ngx-daterangepicker-material

Angular 2+ Date range picker.

Build Status npm version last commit

This Angular Material plugin is compatible with Angular 2+ and is Ivy compatible. It leverages dayjs to handle date manipulation and parsing. The base for this plugin was originally the Bootstrap Date Range Picker, but its dependencies on jQuery, Bootstrap and dayjs.js were removed.

npm.io

Demo: https://fetrarij.github.io/ngx-daterangepicker-material/


Versions

Angularngx-daterangepicker-material
>=12.0.0v6.x.x
<=11.0.0v5.x.x
>=9.0.0v4.x.x
<9.0.0v2.x.x
>=9.0.0 depends on @angular/materialv3.x

Installation

Install the plugin from npm:

npm install ngx-daterangepicker-material --save .

import NgxDaterangepickerMd in your module:

...
import { FormsModule } from '@angular/forms';
import { NgxDaterangepickerMd } from 'ngx-daterangepicker-material';
import { App } from './app';

@NgModule({
    imports: [
        ... ,
        FormsModule,
        NgxDaterangepickerMd.forRoot()
    ],
    declarations: [App],
    bootstrap:    [App]
})
export class AppModule {}

Usage example

Html:

<input type="text" ngxDaterangepickerMd [(ngModel)]="selected" class="form-control"/>

Typescript:

selected: {startDate: Dayjs, endDate: Dayjs};

with some options:

Html:

<input type="text" matInput
    ngxDaterangepickerMd
    [locale]="{applyLabel: 'ok', format: 'DD-MM-YYYY'}"
    startKey="start"
    endKey="end"
    [(ngModel)]="selected"
    name="daterange"/>

Typescript:

selected: {start: Dayjs, end: Dayjs};

You can play with our online demo here and browse our demo code here.

Inline usage

You can use the component directly in your templates, which will set its inline mode to true, in which case the calendar won't hide after date/range selection. You can then use the events: rangeClicked or datesUpdated or choosedDate to get its selection state.

<ngx-daterangepicker-material (choosedDate)="choosedDate($event)">
</ngx-daterangepicker-material>

Available options

autoApply, showDropdowns, singleDatePicker, showWeekNumbers, showISOWeekNumbers, alwaysShowCalendars, showClearButton, showCancel

These options are booleans

isCustomDate

(function) A function that is passed each date in the calendars before they are displayed, and may return a string or array of CSS class names to apply to that date's calendar cell

isInvalidDate

(function) A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not.

isTooltipDate

(function) A function that is passed each date in the two calendars before they are displayed, and may return a text to be displayed as a tooltip.

minDate, maxDate

To set the minimal and maximal date, these options are either a dayjs date or string in ISO format

dateLimit

To set max number of the date we can choose

locale

the locale options is an object with:

{
    format: 'MM/DD/YYYY', // could be 'YYYY-MM-DDTHH:mm:ss.SSSSZ'
    displayFormat: 'MM/DD/YYYY', // default is format value
    direction: 'ltr', // could be rtl
    weekLabel: 'W',
    separator: ' To ', // default is ' - '
    cancelLabel: 'Cancel', // detault is 'Cancel'
    applyLabel: 'Okay', // detault is 'Apply'
    clearLabel: 'Clear', // detault is 'Clear'
    customRangeLabel: 'Custom range',
    daysOfWeek: dayjs.weekdaysMin(),
    monthNames: dayjs.monthsShort(),
    firstDay: 1 // first day is monday
}

Check here for setting the global locale

startKey and endKey

Theses 2 options are for the key you want for the value, default are startDate and endDate, it means the value we have from ngModel are: {startDate: Date, endDate: Date} by default;

Specifiyng startKey and endKey would have different model:

example:

<input type="text" ngxDaterangepickerMd startKey="start" endKey="end" [(ngModel)]="model">

the model we got would be: {start: Date, end: Date}

ranges

(object) Set predefined date ranges the user can select from. Each key is the label for the range, and its value an array with two dates representing the bounds of the range. As an example:

<input type="text" ngxDaterangepickerMd startKey="start" endKey="end" [ranges]="ranges" [(ngModel)]="model">
ranges: any = {
    'Today': [dayjs(), dayjs()],
    'Yesterday': [dayjs().subtract(1, 'days'), dayjs().subtract(1, 'days')],
    'Last 7 Days': [dayjs().subtract(6, 'days'), dayjs()],
    'Last 30 Days': [dayjs().subtract(29, 'days'), dayjs()],
    'This Month': [dayjs().startOf('month'), dayjs().endOf('month')],
    'Last Month': [dayjs().subtract(1, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month')]
  }

Other options with ranges

You can use bellow options when using the ranges. The default are false.

AttributTypeDescription
alwaysShowCalendarsbooleanset to true if you want to display the ranges with the calendar
keepCalendarOpeningWithRangebooleanset to true if you want the calendar won't be closed after choosing a range
showRangeLabelOnInputbooleanset to true if you want to display the range label on input
customRangeDirectionbooleanset to true if you want to allow selection range from end date first
lockStartDatebooleanset to true if you want to lock start date and change only the end date

Open single datepicker from outside

It is possible to open datepicker from outside. You should create an input with attached datepicker directive and a button with "ngx-daterangepicker-action" class (to prevent triggering of clickOutside).

<input
  ngxDaterangepickerMd
  [closeOnAutoApply]="true"
  [autoApply]="true"
  [singleDatePicker]="true"
  [linkedCalendars]="true"
  [(ngModel)]="selected"
  (datesUpdated)="datesUpdated($event)"
  class="datepicker-calendar-icon">

<a class="ngx-daterangepicker-action" (click)="openDatepicker()">
  Open
</a>

In your component's TypeScript file, use the following code to open the datepicker when the trigger is clicked:

  ...
    @ViewChild(DaterangepickerDirective, { static: false }) pickerDirective: DaterangepickerDirective;
  ...
  ...
  openDatepicker() {
    this.pickerDirective.open();
  }

Open multiple datepickers from outside

The approach above works well for a single datepicker, but if you have multiple datepickers on the same page, triggering one will cause all of them to open simultaneously. To avoid this, you can use template reference variables to target each datepicker individually and then call the .focus() event from anywhere.

  <input 
    ngxDaterangepickerMd
    #verifyDatePicker
    [singleDatePicker]="true"
    [(ngModel)]="verifySelected"
    (datesUpdated)="verifyDatesUpdated($event)" 
  />
  <a class="ngx-daterangepicker-action" (click)="verifyDatePicker.focus()"></a>
  <input 
    ngxDaterangepickerMd
    #appointmentDatePicker
    [singleDatePicker]="true"
    [(ngModel)]="aptSelected"
    (datesUpdated)="aptDatesUpdated($event)" 
  />
  <a class="ngx-daterangepicker-action" (click)="appointmentDatePicker.focus()"></a>

In this setup:

  • Each datepicker input is assigned a unique template reference variable (#verifyDatePicker, #appointmentDatePicker).
  • The associated trigger element uses the .focus() method to open the datepicker, ensuring that only the targeted datepicker is activated.

This approach eliminates the need for additional JavaScript code, resulting in a cleaner and more maintainable implementation. Always remember to apply the ngx-daterangepicker-action class to the trigger elements to prevent unintended closures when clicking outside.

Enhancing User Experience with Keyboard Navigation for Multiple Datepickers

Enabling Tab key navigation for multiple datepickers significantly enhances user experience, particularly in forms requiring multiple date inputs, such as booking systems or scheduling applications. This approach improves accessibility by allowing users, including those with disabilities or those who prefer keyboard navigation, to efficiently move through datepicker inputs without relying on a mouse. As users press the Tab key, focus shifts between datepicker inputs, opening each one automatically if configured to do so, which streamlines the date selection process. This method not only increases efficiency and reduces errors but also ensures a consistent and intuitive user experience, making your application more accessible and user-friendly. By adopting this best practice, you cater to a wider range of users, ultimately improving the usability and inclusivity of your forms.

Timepicker

You have to set the attribute timePicker to true if you want to enable the timepicker.

You can use theses options:

AttributTypeDescription
timePicker24Hourbooleanset to true if you want to set the timepicker to 24h instead of having AM and PM
timePickerIncrementnumberset the value increment of the minutes (eg: for 12 there would be 0mn, 15mn, 30mn, 45mn,)
timePickerSecondsbooleanset true if you want do display second's select

Customisation

AttributTypeDescription
firstMonthDayClassstringadd a custom class for all first day of the month
lastMonthDayClassstringadd a custom class for all last day of the month
emptyWeekRowClassstringadd a custom class in a row with a date in a week not in the current month
emptyWeekColumnClassstringadd a custom class for all date in a week not in the current month
lastDayOfPreviousMonthClassstringadd a custom class for the last day of the previous month
firstDayOfNextMonthClassstringadd a custom class for the first day of the next month

Positioning

AttributPossible valuesDescription
opensleft, center, rightposition the calendar from the input element
dropsup, downposition the calendar to the up or down of the calendar

Available events

(rangeClicked)

Fired when clicked on range, and send an object with range label and dates value, eg: {label: 'This Month', dates: [Dayjs, Dayjs]}

(datesUpdated)

Fires when the date model is updated, like applying (if you have activated the apply button), or when selecting a range or date without the apply button, and sends an object containing start and end dates, eg: {startDate: Dayjs, endDate: Dayjs}

(clearClicked)

Fired when clicked on the clear button

Global locale

For setting the global locale, pass this object to NgxDaterangepickerMd.forRoot().

eg:

@NgModule({
    imports: [
        ... ,
        FormsModule,
        NgxDaterangepickerMd.forRoot({
            separator: ' - ',
            applyLabel: 'Okay',
        })
    ],
    declarations: [App],
    bootstrap:    [App]
})

Development

Prepare your environment

Install local dependencies: npm install.

Development server

Run npm start to start a development server on a port 4200.

Open http//:localhost:4200 on your browser.

Tests

Run npm test or ng test to run tests.

License

MIT