Ionic (ionChange) get selected index

2019-08-31 16:37发布

问题:

So I know how to get the selected value using the ionChange event, but how do I get the selected index. For example if i was to select the 3rd value down in a dropdown how can I get the selected index (2) rather than the value selected?

回答1:

You can do something like ths:-

<ion-select placeholder="Select One">
      <ion-select-option value="id1">Value1</ion-select-option>
      <ion-select-option value="id2">Value2</ion-select-option>
</ion-select>

By this when you will select any particular option, then on its change event you will get that object's id instead of the value in the controller.

I hope it helps.



回答2:

This is what you can do to get the id. Add a local variable to your ion-select #selectedIndex. After add your value like this [value]=[prices.w, id]

<ion-select slot="end" (ionChange)="changePrice($event)" #selectIndex>
  <ion-select-option text-uppercase [value]="[prices.w, id]" *ngFor="let prices of prodData?.prices; let id = index" >{{prices.w}}</ion-select-option>
</ion-select>

In your ts. Import ViewChild

import { Component, OnInit, ViewChild } from '@angular/core';

After reference your local variable

@ViewChild('selectIndex') selectedId: ElementRef;

then declare your ionChange() function changePrice(event) and add the following code

public changePrice(event) {
const childCount = this.selectedId['el']['childElementCount'];
this.selectedId['el']['childNodes'][`${childCount}`]['defaultValue'] = event.detail.value[0];
this.selectedId['el']['shadowRoot']['children'][1]['innerHTML'] = event.detail.value[0];
this.selectedId['el']['shadowRoot']['children'][1]['innerText'] = event.detail.value[0];
console.log(event.detail.value[1]);
}

logs your index

console.log(event.detail.value[1]);

Hope it works fine