How to use the getDay method in Ionic 2 / 3

2.4k views Asked by At

I've got an ionic project that is using the ion-segment component to switch between data. The data is categorized from Monday to Sunday. I would like to use the getDay function to automatically pick which day it is and show the relevant segment tab along with its data.

My code thus far is as follows...

home.html

<ion-segment class="segment" color="myYellow" [(ngModel)]="days">
    <ion-segment-button value="monday">
      Mon
    </ion-segment-button>
    <ion-segment-button value="tuesday">
      Tue
    </ion-segment-button>
    <ion-segment-button value="wednesday">
      Wed
    </ion-segment-button>
    <ion-segment-button value="thursday">
      Thu
    </ion-segment-button>
    <ion-segment-button value="friday">
      Fri
    </ion-segment-button>
    <ion-segment-button value="saturday">
      Sat
    </ion-segment-button>
    <ion-segment-button value="sunday">
      Sun
    </ion-segment-button>
  </ion-segment>

<div [ngSwitch]="days">
      <ion-list no-lines *ngSwitchCase="'monday'">
          <ion-item *ngFor="let show of shows">
              <ion-thumbnail item-start>
                <img [src]="show.picture.medium">
              </ion-thumbnail>
              <h4 class="title">{{show.show}}</h4>
              <h6 class="host">{{show.hosts}}</h6>
              <p class="time">{{show.time}}</p>
              <button ion-button clear item-end (click)="showInfo($event, show)">View</button>
            </ion-item>
      </ion-list>

      <ion-list no-lines *ngSwitchCase="'tuesday'">
          <ion-item *ngFor="let show of shows">
              <ion-thumbnail item-start>
                <img [src]="show.picture.medium">
              </ion-thumbnail>
              <h4 class="title">{{show.show}}</h4>
              <h6 class="host">{{show.hosts}}</h6>
              <p class="time">{{show.time}}</p>
              <button ion-button clear item-end (click)="showInfo($event, show)">View</button>
            </ion-item>
      </ion-list>
  </div>

My home.ts file then just has days defined as a string, like this:

days: string = "monday"

My code is working fine with me having to manually select the days on the segment, but I want it to automatically select the day on the segment based on the day of the week when you open the app / page.

1

There are 1 answers

0
David On BEST ANSWER

Just use it as the docs say:

Assuming you have a public days: string; variable which is used in your template for the ngSwitch="days":

In your constructor() body:

let currentDate = new Date();
let weekdays = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
this.days = weekdays[currentDate.getDay()];