Shivam
Shivam

Reputation: 3131

How to select first option in ionic 2 select. selected attribute not working

I am trying to select the first value from the <ion-select>, but it is not working. It is giving true in first(variable). if I print it in the loop. It usually works like this i guess.

dashboard.html

<ion-list>
<ion-item *ngIf="locations != null">
  <ion-label>Location</ion-label>
  <ion-select name="locSelect" #newSelect [(ngModel)]="location" (ionChange)="changeStock(location)">
    <ion-option value="{{loc.id}}" *ngFor="let loc of locations let first = first; let last = last; let i = index;" [selected]="first">{{loc.location_name}}</ion-option>
  </ion-select>
</ion-item>

dashboard.ts

getLocations(id) {
      this.catService.getLocations(id, this.user.apiToken, this.user.role_id).then(result => {
            this.locations = result;

            if(this.user.role_id == 2) {
                this.getDailyItemLogAdmin(this.firstLocationID, this.user.id);
            }else if(this.user.role_id == 3) {
                this.getDailyItemLogManager(this.firstLocationID, this.user.id);
            }

      })
  }

I am calling the above getLocations() function from the constructor.

Upvotes: 1

Views: 2236

Answers (1)

Suraj Rao
Suraj Rao

Reputation: 29614

In your dashboard.ts try setting the ngModel variable location as the first of the locations.

this.catService.getLocations(id, this.user.apiToken, this.user.role_id).then(result => {
            this.locations = result;
            this.location=this.locations[0].id;//here
            let breakIt = false;
            for (let key in this.locations) {
            //...

Upvotes: 1

Related Questions