【问题标题】:How to get index of selected option in Angular如何在Angular中获取所选选项的索引
【发布时间】:2017-10-28 16:14:01
【问题描述】:

我正在尝试使用 Angular 获取 select 的选定选项 index。我正在使用 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>

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

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

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

【问题讨论】:

  • 检查我的答案。 pluker 现在开始工作了
  • 我有点不清楚...你想要索引在哪里?什么变量应该保存索引?
  • indexOf 是否允许在模板中使用?这似乎很棘手,似乎不允许太多:D

标签: javascript angular typescript ionic-framework ionic3


【解决方案1】:

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

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    浪费了3个小时,找到了单行java脚本解决方案。

    您可以使用event.target["selectedIndex"] - 1 来获取选择的selectedIndex

    例子:

    <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;
    }
    

    参考:https://github.com/angular/angular/issues/18842#issuecomment-324399823

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 正如我在问题中提到的,我不想对数组进行交互。
      【解决方案4】:
      <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>
      

      【讨论】:

      • 您的解决方案不适用于我的代码。你能分享一个jsfiddle吗?
      • @YuvrajPatil 你检查我的 plunker 了吗?
      • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
      【解决方案5】:

      使用 (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);
            }
          }
      

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

      【讨论】:

      • OP 要求索引而不是选择的项目。
      • 中不允许 [ng-value]。它的抛出错误。 “无法绑定到 'ngValue',因为它不是 'ion-option' 的已知属性。”
      • 使用 [value]="i" 而不是 ng-value
      • 把 jsfiddle 或 plunker 给我。
      • 您的解决方案是提供选定的索引,但您将索引分配给 select 的 [value],这会从 [(ngModel)] 中删除城市对象,这进一步破坏了选择框的预选择
      猜你喜欢
      • 2019-03-09
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多