我正在使用 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.
}
最佳答案
只需将绑定(bind)添加到 value
<option>
的属性(property)([value]="device.id"
)。请参阅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);
}
}
关于angular - 如何在 Angular 2 (TypeScript) 中获取正确的引用变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33767449/