2017-05-28 55 views
1

我試圖讓所選擇的選項指數一個select的採用了棱角分明。我使用的角度(4)和離子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。

+0

檢查我的答案。現在他們的工作正在進行中 –

+0

我有點不清楚......你想在哪裏找到索引?什麼變量應該保持索引? – Alex

+0

是模板中允許的'indexOf'嗎?這似乎非常棘手,似乎並沒有太多允許:D – Alex

回答

1

使用foreach來基於存在於ngModel如下的值,

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

正如我在我的問題中提到的,我不想介紹一個數組。 –

1

使用(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

+0

你的運動員在工作嗎? – Aravind

+0

是的,它現在的工作 –

+0

OP問索引,而不是選擇的項目。 – Aravind

1
<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> 
+1

你的解決方案不適用於我的代碼。你能分享一個jsfiddle嗎? –

+0

@YuvrajPatil你檢查過我的搶劫者嗎? –

+0

儘管此代碼可能會回答問題,但提供有關如何解決問題和/或爲何解決問題的其他上下文會提高答案的長期價值。 – Badacadabra

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

希望這有助於。