2

I am using Angular 2 (TypeScript).

I have a class which looks like this:

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

I want to show device label in dropdown list, but in onChange() I want to get device ID. What can I do? Thank you!

<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 Answer 1

2

Just add a binding to a 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);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, alexpods, especially the link to W3!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.