Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ionic 2 DatePicker

Tags:

ionic2

cordova

I'm new to ionic and I'm playing with ionic 2 beta. I'm trying to implement a native datepicker using cordova plugin like in the documentation.

I've fully copy/paste the example, and I get "ReferenceError: DatePicker is not defined on Nexus 5 Emulator and Archos android phone.

openDatePicker() {
    var options = {
      date: new Date(),
      mode: 'date'
    };

    function onSuccess(date) {
        alert('Selected date: ' + date);
    }

    function onError(error) { // Android only
        alert('Error: ' + error);
    }

    DatePicker.show(options, onSuccess, onError);
  }

I've searched a lot and found nothing about this, maybe I'm doing it wrong with cordova plugin on Ionic 2?

like image 995
MokaT Avatar asked Mar 05 '16 14:03

MokaT


2 Answers

The documentation on this is lacking (the Ionic Native docs at the time of this question are still very much a WIP).

ionic-native is a separate module from the framework, so you'll need to install it:

# from within your project directory
npm install --save ionic-native

You'll also need to install the plugin you're trying to use if you haven't already:

#from within your project directory
ionic plugin add cordova-plugin-datepicker

Then import the DatePicker plugin in your code:

import {DatePicker} from 'ionic-native';

And then same as Ionic 1 you won't be able to use any plugins until Cordova is ready. This means you can either use Platform.ready or wait for the deviceready event to fire on window:

constructor(platform: Platform) {
  platform.ready().then(() => {
    let options = {
      date: new Date(),
      mode: 'date'
    }

    DatePicker.show(options).then(
      date => {
        alert('Selected date: ' + date);
      },
      error => {
        alert('Error: ' + error);
      }
    );
  });
}

Also one thing to note is that ionic-native wraps the callbacks in a promise.

like image 197
user1234 Avatar answered Oct 30 '22 04:10

user1234


Try this:

step 1: npm install @ionic-native/core --save
step 2: npm install --save @ionic-native/date-picker
step 3: add this plugin to your app.module.ts
          i. import { DatePicker } from '@ionic-native/date-picker';
         ii. providers:[DatePicker]
step 4: import { DatePicker } from '@ionic-native/date-picker';
step 5: Inject in constructor:
        constructor(public datePicker: DatePicker) { }
step 6: You can access datePicker like: 
        this.datePicker.show({
         date: new Date(),
             mode: 'date',
             androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_DARK
         }).then(
             date => console.log('Date: ', date),
             err => console.log('Error while getting date: ', err)
         ); 
like image 45
Raj Kumar Avatar answered Oct 30 '22 04:10

Raj Kumar