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

标签 angular

我正在使用 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/

相关文章:

javascript - 从服务内部的 Url 获取 Json

Angular 在模板中创建一个递归循环来呈现评论树

angular - 从 Promise 内部返回已解决的 Observable

angular - 在 '...ge-2.2.1.tgz"附近解析时出现错误 JSON 输入意外结束} ,"engin'

angular - karma-jasmine-html-reporter@1.1.0 需要 jasmine@>=3 的对等体,但没有安装。

angular - 直接在 Angular 6 中加载页面

javascript - 使用 Angular Material 2 在文本区域中查找选定的文本

angular - 每次服务器响应+延迟后轮询服务器

javascript - 将多个服务插入服务 - angular2

sqlite - 我如何将数据传递到我的 SQLite 数据库中