V. Pivet
V. Pivet

Reputation: 1328

Ionic 2 : ion-datetime return empty value

I use an ion-datetime picker in one of my page to select only a month. I wrote this in my .html :

    <ion-item>
          <ion-label>Mois</ion-label>
          <ion-datetime [(ngModel)]="month"
                        displayFormat="MMMM"
                        monthNames="Janvier, Février, Mars, Avril, Mai, Juin, Juillet, Aout, Septembre, Octobre, Novembre, Décembre"
                        doneText="Valider" cancelText="Annuler">
         </ion-datetime>
   </ion-item>

But when I pick a month with this field, I have an empty value.

My .ts file :

month: any  = null;

  constructor(public viewCtrl: ViewController) {

  }

  dismiss() {
    this.viewCtrl.dismiss();
  }

  test() {
    console.log(this.month);
  }

Any Idea ?

Upvotes: 0

Views: 934

Answers (1)

emroussel
emroussel

Reputation: 1147

I also ran into similar problems using Ionic's DateTime component.

Initializing the value bound to ngModel seemed to fix it for me, although this will give a default value to the picker (which might be useful depending on your use case).

Ionic's DateTime works in ISO 8601 format, so doing something like this in your constructor would give the picker a default value of the current month

constructor(public viewCtrl: ViewController) {
  this.month = (new Date()).toISOString();
}

The value of month will be updated when the picker changes, but it will be in ISO 8601 format again, so you'll have to extract the month from it if that is the value you are looking for.

I would be happy to know if there is a cleaner solution for this!

Upvotes: 1

Related Questions