Questions tagged [ngx-mydatepicker]

Use this for questions about the ngx-mydatepicker package for Angular 2+

Description Angular attribute directive date picker. Compatible Angular2+.

There is similar date picker here, but difference between these two is that with the ngx-mydatepicker you can define the style of input box, calendar and clear buttons.

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

npm install ngx-mydatepicker --save

Add MyDatePickerModule import to your @NgModule like example below

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MyTestApp } from './my-test-app';
import { NgxMyDatePickerModule } from 'ngx-mydatepicker';

@NgModule({
    imports:      [ BrowserModule, NgxMyDatePickerModule.forRoot() ],
    declarations: [ MyTestApp ],
    bootstrap:    [ MyTestApp ]
})
export class MyTestAppModule {}

If you are using systemjs package loader add the following ngx-mydatepicker properties to the System.config:

(function (global) {
    System.config({
        paths: {
            'npm:': 'node_modules/'
        },
        map: {
            // Other components are here...

            'ngx-mydatepicker': 'npm:ngx-mydatepicker/bundles/ngx-mydatepicker.umd.min.js'
        },
        packages: {
        }
    });
})(this);

Usage Use one of the following two options.

  1. ngModel binding In this option the ngModel binding is used. Here is an example application. It shows how to use the ngModel.

To use ngModel define the application class as follows:

import {INgxMyDpOptions, IMyDateModel} from 'ngx-mydatepicker';
// other imports here...

export class MyTestApp {

    myOptions: INgxMyDpOptions = {
        // other options...
        dateFormat: 'dd.mm.yyyy',
    };

    // Initialized to specific date (09.10.2018)
    model: any = { date: { year: 2018, month: 10, day: 9 } };

    constructor() { }

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

Add the following snippet inside your template:

<!-- input box styling is bootstrap 3.3.7 -->
<form>
    <div class="input-group">
        <input class="form-control" style="float:none" placeholder="Select a date" ngx-mydatepicker name="mydate"
               [(ngModel)]="model" [options]="myOptions" #dp="ngx-mydatepicker" (dateChanged)="onDateChanged($event)"/>

        <span class="input-group-btn">
            <button type="button" class="btn btn-default" (click)="dp.clearDate()">
                <i class="glyphicon glyphicon-remove"></i>
            </button>
            <button type="button" class="btn btn-default" (click)="dp.toggleCalendar()">
                <i class="glyphicon glyphicon-calendar"></i>
            </button>
        </span>
    </div>
</form>

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

Initialize with the IMyDate object: // Initialized to specific date (09.10.2018) model: any = { date: { year: 2018, month: 10, day: 9 } }; Initialize with the JS date object: // Initialized to today model: any = { 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 {INgxMyDpOptions} from 'ngx-mydatepicker';
    // other imports here...

    export class MyTestApp implements OnInit {

    myOptions: INgxMyDpOptions = {
        // other options...
        dateFormat: 'dd.mm.yyyy',
    };

    private myForm: FormGroup;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.myForm = this.formBuilder.group({
            // Empty string or null means no initial value. Can be also specific date for
            // example: {date: {year: 2018, month: 10, day: 9}} which sets this date to initial
            // value.

            myDate: [null, Validators.required]
            // other controls are here...
        });
    }

    setDate(): void {
        // Set today date using the patchValue function
        let date = new Date();
        this.myForm.patchValue({myDate: {
        date: {
            year: date.getFullYear(),
            month: date.getMonth() + 1,
            day: date.getDate()}
        }});
    }

    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 3.3.7 -->
<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
    <div class="input-group">
        <input class="form-control" style="float:none" placeholder="Select a date" ngx-mydatepicker name="myDate"
               formControlName="myDate" [options]="myOptions" #dp="ngx-mydatepicker"/>

        <span class="input-group-btn">
            <button type="button" class="btn btn-default" (click)="dp.clearDate()">
                <i class="glyphicon glyphicon-remove"></i>
            </button>
            <button type="button" class="btn btn-default" (click)="dp.toggleCalendar()">
                <i class="glyphicon glyphicon-calendar"></i>
            </button>
        </span>
    </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>

Example of the options data (not all properties listed): myOptions: INgxMyDpOptions = { todayBtnTxt: 'Today', dateFormat: 'yyyy-mm-dd', firstDayOfWeek: 'mo', sunHighlight: true, disableUntil: {year: 2016, month: 8, day: 10} }; defaultMonth attribute If initial date is not specified, when the calendar is opened, it will ordinarily default to selecting the current date. If you would prefer a different year and month to be the default for a freshly chosen date picking operation, specify a defaultMonth attribute.

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 ngx-mydatepicker name="mydate" [(ngModel)]="model" [options]="myOptions" #dp="ngx-mydatepicker"/>

This #dp="ngx-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 ngx-mydatepicker [(ngModel)]="model" [options]="myDatePickerOptions" #dp="ngx-mydatepicker"/>
@ViewChild('dp') ngxdp: NgxMyDatePickerDirective;

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

Callbacks dateChanged callback called when the date is selected, removed or input field typing is valid

event parameter:

event.date: Date object in the following format: { day: 22, month: 11, year: 2016 } event.jsdate: Javascript Date object event.formatted: Date string in the same format as dateFormat option is: '2016-11-22' event.epoc: Epoc time stamp number: 1479765600 event parameter type is IMyDateModel

Example of the dateChanged callback:

onDateChanged(event: IMyDateModel) {
  console.log('onDateChanged(): ', event.date, ' - jsdate: ', new Date(event.jsdate).toLocaleDateString(), ' - formatted: ', event.formatted, ' - epoc timestamp: ', event.epoc);
}

inputFieldChanged callback called when the value change in the input field, date is selected or date is cleared (can be used in validation, returns true or false indicating is date valid or not in the input field)

event parameter:

event.value: Value of the input field. For example: '2016-11-22' event.dateFormat: Date format string in the same format as dateFormat option is. For example: 'yyyy-mm-dd' event.valid: Boolean value indicating is the input field value valid or not. For example: true event parameter type is IMyInputFieldChanged

Example of the input field changed callback:

onInputFieldChanged(event: IMyInputFieldChanged) {
  console.log('onInputFieldChanged(): Value: ', event.value, ' - dateFormat: ', event.dateFormat, ' - valid: ', event.valid);
}

calendarViewChanged callback called when the calendar view change (year or month 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:

onCalendarViewChanged(event: IMyCalendarViewChanged) { console.log('onCalendarViewChanged(): Year: ', event.year, ' - month: ', event.month, ' - first: ', event.first, ' - last: ', event.last); } 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:

  onCalendarToggle(event: number): void {
      console.log('onCalendarClosed(): Reason: ', event);
  }

Development of this component At first fork and clone this repo.

Install all dependencies:

npm install npm install --global gulp-cli Build the npmdist folder and execute tslint:

gulp all Execute unit tests and coverage (output is generated to the test-output folder):

npm test Run sample application:

npm start Open http://localhost:5000 to browser Build a local npm installation package:

gulp all cd npmdist npm pack local installation package is created to the npmdist folder. For example: ngx-mydatepicker-0.0.1.tgz Install local npm package to your project:

npm install path_to_npmdist/ngx-mydatepicker-0.0.1.tgz

9 questions
2
votes
2 answers

ngx-mydatepicker - Position of Calendar is not aligned to input

I am using ngx-mydatepicker from https://www.npmjs.com/package/ngx-mydatepicker Its functioning properly, however, after clickin on textbox it is opening the calendar which is not aligned to the textbox The code is as below html:
captainsac
  • 2,484
  • 3
  • 27
  • 48
1
vote
1 answer

does the filter with new date() accept format other than yyyy-mm-dd?

I have a response from mydatepicker in the following format { "isRange":false, "singleDate":{ "date":{ "year":2022, "month":5, "day":13 }, "jsDate":"2022-05-13T03:00:00.000Z", "formatted":"13-05-2022", "epoc":1652410800 …
Leonardo
  • 47
  • 6
1
vote
1 answer

date in ng2-smart-table is not displaying

I'm trying to add and display my data using smart table using angular 10 one of the table columns is the date I installed mydatepicker I made a component called calendar here's calendar.ts import { Component, Input, OnInit } from…
derpinette
  • 41
  • 5
1
vote
1 answer

how to conditionally add mydatepicker disablescince prop only for a particular field in angular

present mydatepicker options are as below: in ts file myDatePickerOptions: IMyDpOptions = { // other options... dateFormat: 'dd-mmm-yyyy', editableDateField: false, openSelectorOnInputClick: true, }; html file:
Monika
  • 149
  • 1
  • 2
  • 8
0
votes
2 answers

Set myDatePicker so PlaceHolder is shown

I have a record where no End Date has been defined. I can not figure out how to set the myDatePicker such that the place holder is shown to be clear, this is the control I am using https://github.com/kekeh/angular-mydatepicker/wiki import {…
greg
  • 1,673
  • 1
  • 17
  • 30
0
votes
1 answer

How to clear manual input date in angular ngx-mydatepicker

I am working in ngx-mydatepicker to select dates in my Angular(11) app. I followed the URL https://github.com/kekeh/ngx-mydatepicker and I am able to get the datepicker as expected. I have implemented the reactive forms in my application, I did the…
DevGo
  • 1,045
  • 1
  • 16
  • 42
0
votes
0 answers

Card overlaps Angular mydatepicker selector

enter image description here I integrated Bootstrap, Jquery with Angular 9. I used jquery data table, Angular Mydatepicker, Angular Select and Bootstrap Card . Card is overlapping select dropdown and datepicker selector. I used Bootstrap 4 and…
0
votes
0 answers

How to change the weekends from Saturday/Sunday to other days

https://github.com/kekeh/ngx-mydatepicker#options-attribute weekend is not saturday/sunday how can I fix the default weekend days?
AGS
  • 1
  • 2
0
votes
1 answer

How to compare two dates in angular 4 and display error message?

I want to display an error message when end date is less than start date. I'm using my-date-picker. I have tried following approach but not sure why its not working. As I'm new to angular I tried this approach by going online tutorials, this is what…
Uidev123
  • 73
  • 3
  • 13