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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44224085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:35:20  来源:igfitidea点击:

How to get index of selected option in Angular

javascriptangulartypescriptionic-frameworkionic3

提问by Yuvraj Patil

I am trying to get the selected option indexof a selectusing Angular. I am using Angular (4) and Ionic 3.

我试图让所选择的选项指标select采用了棱角分明。我正在使用 Angular (4) 和 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 selectedCityIndexin component.

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

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.

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

回答by Omkar Porje

If you want index in the component class file, please check this plnkr https://plnkr.co/edit/9Z7jjeSW7fmTUR7SbqNk?p=preview

如果你想在组件类文件中索引,请检查这个 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.

希望这可以帮助。

回答by Aravind

Use forEach to iterate based on the value present in ngModelas below,

使用 forEach 根据存在的值进行迭代ngModel,如下所示,

this.cities.forEach((city,index) => {
   if(city ==== obj.city){
       selectedIndex= index;
    }
})

回答by Dinesh undefined

Use (ngModelChange). The (ngModelChange) event listener emits events when the selected value changes.

使用(ngModelChange). (ngModelChange) 事件侦听器在选定值更改时发出事件。

 @Component({
      selector: 'my-app',
      template: `
        <h2>Select demo</h2>
        <select [(ngModel)]="selectedCity" (ngModelChange)="onChange($event)" >
          <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option>
        </select>
      `
    })
    class App {
      cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}];
      selectedCity = this.cities[1];

      onChange(city) {
        alert(city.name);
      }
    }

Example: https://plnkr.co/edit/tcnPfCplQbywbBHVsiUy?p=preview

示例:https: //plnkr.co/edit/tcnPfCplQbywbBHVsiUy?p=preview

回答by Yoav Schniederman

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