如何在 Angular 2 (TypeScript) 中获取正确的引用变量值?

How to get correct reference variable value in Angular 2 (TypeScript)?

我正在使用 Angular 2 (TypeScript)。

我有一个 class 看起来像这样:

class Device{
    id:string;
    label:string;
}

我想在下拉列表中显示设备标签,但在 onChange() 中我想获取设备 ID。我能做什么?谢谢!

<select #device (change)="onChange($event, device.value)">
    <option *ng-for="#i of devices.label">{{i}}</option>
</select>

onChange($event, deviceValue) {
    console.log(deviceValue);
    // Right now deviceValue is device label, however I want to get device ID.
}

只需将绑定添加到 value property of an <option> ([value]="device.id"). See this plunk:

import {Component, NgFor} from 'angular2/angular2'

@Component({
  selector: 'my-app',
  directives: [NgFor],
  template: `
    <select #device (change)="onChange($event, device.value)">
      <option *ng-for="#device of devices" [value]="device.id">
        {{ device.label }}
      </option>
    </select>
  `
})
export class App {
  constructor() {
    this.devices = [
      { id: 1, label: 'Nokia'    },
      { id: 2, label: 'Motorola' },
      { id: 3, label: 'iPhone'   }
    ]
  }

  onChange(event, deviceValue) {
    console.log(deviceValue);
  }
}