I am testing the ionic V7 ion-datetime I am able to bind the (ionChange) to an [(ngModel)] and format the change. What I am trying to do is link the ion-datetime-button to an [(ngModel)] and format to YYYY-MM-DD. is this possible.
html
<ion-datetime-button datetime="TESTID"></ion-datetime-button>
<ion-modal [keepContentsMounted]="true">
<ng-template>
<ion-datetime
#popoverDateMain
[showDefaultButtons]="true"
id="TESTID"
presentation="date"
displayFormat="YYYY-MM-DD" // Does nothing
min="{{minDateAvailable}}"
max="{{today}}"
(ionChange)="item.Input = formatDate(popoverDateMain.value)" // links to [(ngModel)]
>
</ion-datetime>
ts
import { format, parseISO } from 'date-fns';
formatDate(value: any) { return format(parseISO(value), 'yyyy-MM-dd'); }
getToday() {
this.today = this.formatDate(new Date().toISOString())
return this.today;
}
minDate(){
this.min = new Date();
this.min.setMonth( this.min.getMonth()-6)
this.min = this.min.toISOString();
this.minDateAvailable = this.formatDate(this.min);
return this.minDateAvailable;
}
Maybe I'm missing something in what you're trying to achieve here, but it seems you're simply overthinking/overcomplicating it.
If you set ngModel
directly to a string in the desired and supported format, it should just work.
Here's a bare-bones example that should get you going:
TS...
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
@Component({
selector: 'app-datepicker',
templateUrl: './datepicker.page.html',
styleUrls: ['./datepicker.page.scss'],
standalone: true,
imports: [IonicModule, CommonModule, FormsModule]
})
export class DatepickerPage {
#date: string = '2023-04-20T12:00';
get date(): string { return this.#date };
set date(val: string) {
this.#date = val;
console.log(this.date);
};
constructor() { }
}
HTML...
<ion-header [translucent]="true">
<ion-toolbar>
<ion-title>Date Picker Test</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-datetime-button datetime="datetime"></ion-datetime-button>
<ion-modal [keepContentsMounted]="true">
<ng-template>
<ion-datetime
id="datetime"
[(ngModel)]="date"
>
</ion-datetime>
</ng-template>
</ion-modal>
</ion-content>
Here's some console output changing the date or time...
datepicker.page.ts:18 2023-04-06T12:00:00
datepicker.page.ts:18 2023-04-06T13:00:00
If I'm missing something please say and I can see about updating this.
Here's a repo with the code.