ionic 2 DatePicker

不想你离开。 提交于 2020-01-14 08:44:06

问题


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?


回答1:


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.




回答2:


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)
         ); 


来源:https://stackoverflow.com/questions/35815279/ionic-2-datepicker

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!