Search code examples
angulardatetimeionic-frameworkionic3ngmodel

Ionic 3 ion-datetime display format without year ngModel will blank


I am build up the form in ionic 3 app, and have a birthday input using ion-datetime. For some privacy reason, I can't get the people birth year. But when I set the ion-datetime format with DD MMMM. the ngModel is blank, but when I have year e.g. DD MMMM YYYY, it will normal get the user input. May I know how to solve it? below is my code:

<ion-datetime displayFormat="DD MMMM" [(ngModel)]="formData.birthday"></ion-datetime>

And the stackblitz:

https://stackblitz.com/edit/ionic-9q3aas?file=pages%2Fabout%2Fabout.html


Solution

  • This is indeed a very strange issue!

    I think the issue is because of this line of code of Ionic's source code:

    _inputNgModelEvent(): any {
      return convertDataToISO(this.value);
    }
    

    Seems like Ionic is trying to convert the selected values to an ISO date, but if the year is not there, then it's not a valid ISO date. One workaround would be to listen to the ionChange event directly, like this:

    <ion-header>
      <ion-navbar>
        <ion-title>
          Test
        </ion-title>
      </ion-navbar>
    </ion-header>
    
    <ion-content padding>
      <ion-item>
      <ion-label>Value</ion-label>
      <ion-datetime 
        displayFormat="DD MMMM"
        (ionChange)="updateValues($event)" <--- here!
      ></ion-datetime>
    
      </ion-item>
      <ion-item>
        <button ion-button (click)="printValues()">Show Result in Console</button>
      </ion-item>
    </ion-content>
    
    

    And then in your component code you can handle that event to get the selected values:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'page-test',
      templateUrl: 'test.html'
    })
    export class TestPage {
      public day: number;
      public month: number;
    
      updateValues(values: any) {
        if(values) {
          this.day = values.day;
          this.month = values.month;
        }
      }
    
      printValues() {
        console.log(`day: ${this.day}`);
        console.log(`month: ${this.month}`);
      }
    }
    
    

    Please take a look at the updated stackblitz demo.