Umaiz Khan
Umaiz Khan

Reputation: 1227

Ionic 3 Set date from selected date

In my project I need to show the date of vaccination of a child. For example, if the user selects date 2/16/2019, then the other 3 date will be 5/16/2019, 7/16/2019 & 9/16/2019. When the user selects a date then other dates will show in gaps of 2 days.

 <ion-content>
     <ion-item>
            <ion-label floating>Date</ion-label>
            <ion-datetime  displayFormat="DD/MMMM/YYYY" min="2010" max="2050-10-31" formControlName="birthday" > //if user example select 2/16/19
            </ion-datetime>
    </ion-item>
    <div> 
        <h1>first vaccine</h1>
        <p> here comes the date of selected date after 2 days</p> //here come 2/18/19
    </div>
</ion-content>

Upvotes: 1

Views: 668

Answers (1)

Sudarshana Dayananda
Sudarshana Dayananda

Reputation: 5265

You can do this using ionChange event of ion-datetime. According to selected date add upcoming 3 days to another array and loop in you HTML as below.

TS

export class HomePage {

  selectedDate: Date;
  upcomingDates: any[];

  constructor() {}

  onDateChange() {

    let upcomingIteration = ['First', 'Second', 'Third'];
    this.upcomingDates = [];

    for (let i = 1; i < upcomingIteration.length + 1; i++) {
        let tempDate = new Date(this.selectedDate);
        let upcomingDate = tempDate.setDate(tempDate.getDate() + i * 2);
        this.upcomingDates.push({ time: upcomingIteration[i -1], date: new Date(upcomingDate)}); 
    }
    console.log(JSON.stringify(this.upcomingDates, null, 2));
  }
}

HTML

<ion-content padding>
  <h2>Date of vaccinations of child</h2>
  <ion-item>
    <ion-label floating>Date</ion-label>
      <ion-datetime [(ngModel)]="selectedDate"  displayFormat="DD/MMMM/YYYY" min="2010" max="2050-10-31" (ionChange)="onDateChange()"> 
    </ion-datetime>
</ion-item>

<div style="margin-top: 25px;" *ngIf="selectedDate"> 
  <div *ngFor="let commingDate of upcomingDates">
    <p>{{commingDate.time }} : {{commingDate.date | date}}</p>
  </div>
</div>
</ion-content>

Find Working StackBlitz Demo Here.

Upvotes: 1

Related Questions