如何在 ion-select 中获取所选项目的索引

Cod*_*ger 1 ionic2 ion-select

我正在使用<ion-select>下拉列表,它按预期工作,但我在这里想要的是所选选项的索引<ion-select>

我已经使用<ion-select>并更改了事件,如下所示:

<ion-select class="myCustomSelect" [(ngModel)]="selectedProductDD" interface="popover" (ionChange)="onSelectChange($event)">
    <ion-option *ngFor="let selectedProduct of productArray" [value] = selectedProduct.pid>{{ selectedProduct.pid }} </ion-option>
</ion-select>
Run Code Online (Sandbox Code Playgroud)

更改事件:

onSelectChange(selectedValue: any) {
   //Here I want Index also.
   //Currently I am getting selected Value.
}
Run Code Online (Sandbox Code Playgroud)

让我知道是否有人可以帮助我!

提前致谢。

Gab*_*eto 6

在您中*ngFor,您还可以定义一个变量来接收 que 索引

<ion-select class="myCustomSelect" [(ngModel)]="selectedProductDD" interface="popover" (ionChange)="onSelectChange($event)">
  <!-- you can also have your index by declaring a variable in ngFor that'll receive the index -->
  <ion-option *ngFor="let selectedProduct of productArray; let i = index" [value] = selectedProduct.pid>{{ selectedProduct.pid }} </ion-option>
</ion-select>
Run Code Online (Sandbox Code Playgroud)

这里的情况是您声明的索引位于您的内部ion-select,因此它不可用于onSelectChange方法。因此,在您的 .TS 文件中声明一个属性

public myIndex: number = 0;
Run Code Online (Sandbox Code Playgroud)

每次用户选择一个选项时,该属性都会收到索引

<!-- on selecting an option your myIndex will receive the current selected option index -->
<ion-option *ngFor="let selectedProduct of productArray; let i = index" [value]=selectedProduct.pid (ionSelect)="myIndex = i">{{ selectedProduct.pid }}</ion-option>
Run Code Online (Sandbox Code Playgroud)

然后你就可以在你的onSelectChange()

onSelectChange(selectedValue: any) {
  let index = this.myIndex;
}
Run Code Online (Sandbox Code Playgroud)

还有另一种选择,但这是最有角度的方法。希望这可以帮助。