首页 文章

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

提问于
浏览
2

我正在使用Angular 2(TypeScript) .

我有一个看起来像这样的课:

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

1 回答

  • 2

    只需将绑定添加到 <option>[value]="device.id" )的value属性即可 . 见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);
      }
    }
    

相关问题