How to get index of selected option in Angular

Viewed 25482

I am trying to get the selected option index of a select using Angular. I am using Angular (4) and Ionic 3.

My template looks like below:

<ion-select [(ngModel)]="obj.city">
   <ion-option *ngFor="let city of cities; let i = index;" 
                [value]="city"  [selected]="i == 0">
                {{city.name}}
   </ion-option>
</ion-select>

I want the index of selected city to be accessed in Component code. Lets say, I want that index to be assigned to a variable selectedCityIndex in component.

My current code is pre selecting the first option as default. Solution should not break this functionality.

I am searching for a solution which do not include interating the array (i.e. no loop in JavaScript part). It should not use "indexOf" method or document's methods like "document.getElementById". I am not using jQuery.

5 Answers

After wasting 3 hours, I found a single line java script solution.

you can use event.target["selectedIndex"] - 1 to get the selectedIndex of select.

Example:

<select class="form-control selectpicker" #Code name="Code" [(ngModel)]="model.Code" (change)="searchWithCode($event)" >
    <option value="" selected="selected">--Please select--</option>
    <option *ngFor="let x of Codes" [value]="x.Code" [selected]="x.Code == model.Code">{{x.Name}}</option>
</select>



searchWithCode(event:Event) : void {
    let index:number = use event.target["selectedIndex"] - 1;
}

Reference: https://github.com/angular/angular/issues/18842#issuecomment-324399823

Related