2015-11-17 25 views
2

我正在使用Angular 2(TypeScript)。如何在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. 
} 

回答

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); 
    } 
} 
+0

非常感謝你,alexpods,特別是鏈接到W3! –

相關問題