Ionic ion-datetime: how to set default picker value without changing the model?


#1

Hi,

I am trying to emulate the default device datetime picker’s behavior with Ionic 2 but couldn’t find any solution.
What I want is basically set the datetime picker’s value to current date and time even when model has no value.
I know if I set the model I can get it to work but I need to keep the datetime box clear and when user taps on the box the picker opens with current date/time instead of showing 1/1/16 or 1:00 PM as it does now.

I’m thinking if there is any picker opened event that allows to set the picker’s selected value, that would be a solution.
I would appreciate any thought on this.


Ionic, ion-datetime show today's date selected when picker popped up
#2

Have you found any solution ? Am facing the same problem


#3

Y’all can chime in on #9846 if you feel strongly about this.


#4

Until there is some inbuilt mechanism to do this, you can try the following work around:

  1. Declare a variable in the component code, say defdt, and initialise it to an empty string ""
  2. In the template <ion-datetime> mark up, set defdt as the [(ngModel)] and add an event handler to the (tap) event
  3. In the component code of the (tap) event handler, set defdt to the date you want the datetime to open with (check for state and apply logic accordingly)
  4. Handle the ionCancel event yourself and reset everything as per the state and app logic

This should give you the result you are looking for.


#5

Thanks ! With (tap) event handler and [(ngModel)] it works ! :slight_smile: