如何在 Angular 中获取所选选项的索引

Yuv*_*til 3 javascript typescript ionic-framework ionic3 angular

我试图让所选择的选项指标select采用了棱角分明。我正在使用 Angular (4) 和 Ionic 3。

我的模板如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

我希望在组件代码中访问所选城市的索引。可以说,我希望将该索引分配给selectedCityIndex组件中的一个变量。

我当前的代码是预先选择第一个选项作为默认值。解决方案不应破坏此功能。

我正在寻找一种不包括数组交互的解决方案(即 JavaScript 部分没有循环)。它不应该使用“indexOf”方法或文档的方法,如“document.getElementById”。我没有使用 jQuery。

小智 7

如果你想在组件类文件中索引,请检查这个 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 {}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。