Reputation: 430
I am using ion-datetime with my form. I want to add by default to my form the Year even before the user chooses the year from the datepicker.
here is my code:
HOME.html
<ion-content padding>
<div>
<form [formGroup]="rForm" (ngSubmit)="addPost(rForm.value)">
<ion-list>
<ion-item>
<ion-label colot="primary" floating>
Year
</ion-label>
<ion-datetime displayFormat="YYYY" formControlName="year" min="2000" max="{{date| date:'yyyy'}}" [disabled]="!user"></ion-datetime>
</ion-item>
<ion-item>
<button ion-button block [disabled]="!user" (click)="addToTracker(rForm.value)">Submit To Tracker</button>
</ion-item>
</ion-list>
</form>
</div>
HOME.ts significant code:
this.date = new Date();
Now this works and I can correctly take the Year once its picked by the user (I do not want anything other then the year) The problem is the user can submit the form with the year field empty. In order to over come that (I do not want to use ngModel because i tried it and it did not allow me to use only the Year, it wanted an ISO date format so once submitted i got a full date and not just the year, i do not know if there is another way for ngModel)
So my idea is to put the current YEAR by default there... so in case the user submitted without a year it will take 2017 by default.
I'm open to suggestions!
Thanks a lot.
Upvotes: 1
Views: 2876
Reputation: 11
Below is the code for TS file, Date should be converted to ISO String to render properly in Ionic 2/3/4
Add in ts allow user to select date with future years.
minDate: string = new Date().toISOString();
maxData : any = (new Date()).getFullYear() + 3;
Upvotes: 0
Reputation: 181
Too late but maybe someone else need it. (for Ionic 4) firstly you could use ngmodel for this;
add this to ts file date:number =2017;
<ion-datetime display-format="YYYY" [(ngModel)]="date" formControlName="year" min="2000" max="{{date| date:'yyyy'}}" [disabled]="!user"></ion-datetime>
and other option add [value]="2017"
<ion-datetime display-format="YYYY" [value]="2017" formControlName="year" min="2000" max="{{date| date:'yyyy'}}" [disabled]="!user"></ion-datetime>
Upvotes: 0
Reputation: 2736
Below is the code for TS file, date should be converted to ISOString to render properly in Ionic
date : any = new Date().toISOString();
currentYear : any = (new Date()).getFullYear();
Below is the code for HTML file
<ion-datetime displayFormat="YYYY" min="2000" max="{{currentYear}}" [(ngModel)]="date"></ion-datetime>
Refer the link for working version.
Upvotes: 1