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.
If you want index in the component class file, please check this plnkr https://plnkr.co/edit/9Z7jjeSW7fmTUR7SbqNk?p=preview
//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<h2>Select demo</h2>
<select (change)="onChange($event.target.value)" >
<option *ngFor="let c of cities;let i = index" [value]="i"> {{c.name}} </option>
</select>
`
})
class App {
public value:integer;
cities = [{'name': 'Pune'}, {'name': 'Mumbai'}, {'name': 'Nagar'}];
selectedCity = this.cities[1];
constructor() {
this.value = 0;
}
onChange(cityindex) {
console.log(cityindex);
alert(cityindex);
}
}
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Hope this helps.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With