在选择 - 角度2中选择的选项的位置

时间:2018-01-16 11:23:44

标签: html angular

如何获得我选择的option的位置。我应该像桌子的index一样工作:

在表格中

<tr *ngFor="let car of cars;let i = index" (click)="showTabs(i)">
   <td>{{i+1}}</td>
</tr>

我希望得到这个但是为select

工作

我尝试过选择

<select (change)="getPos(i);" required>
    <option *ngFor="let car of cars;let i = index">whatever</option>
</select>

2 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是使用HTMLSelectElement.selectedIndex属性,例如:

(change)="index = $event.target.selectedIndex"

答案 1 :(得分:1)

当您选择时,您可以为选项提供“值”。您可以选择“value = index”,然后在$ event.target.value中选择“index”

<select (change)="getValue($event);" required>
    <option *ngFor="let car of cars;let i = index" [value]="i">{{car}}</option>
</select>
getValue(event:any)
{
  let index:number=+event.target.value; //event.target.value is a string
  console.log(event.target.value,index);
}

或者您可以选择获取值并使用findIndex

<select (change)="getValue($event);" required>
    <option *ngFor="let car of cars;let i = index" [value]="car.id">{{car}}</option>
</select>
getValue(event:event)
{
  //if your cars if some like [{id:1,name:"lamborggini"},{id:2,name="porche"}..]
  let index:number=cars.findIndex(c=>c.id==event.target.value;
  console.log(event.target.value,index);
}