1

I have the following HTML which 2-way binds the option text to the newNumber instance variable.

 <select id="inputState" [(ngModel)]="newNumber" name="newNumber" class="form-control">
    <option data-value-x="192" data-value-y="108" selected="selected"> First</option>
    <option data-value-x="128" data-value-y="72">Second </option>
    <option data-value-x="108" data-value-y="108">Third </option>
    <option data-value-x="72"  data-value-y="72">Forth</option>
 </select>

I would like to access data-value-x and data-value-y for the selected option. This can I do that the Angular way?

1 Answer 1

3

Just bind the select to an object containing the values:

    <select name="point" [(ngModel)]="point">
      <option></option>
      <option [ngValue]="{x: 192, y: 108}">First</option>
      <option [ngValue]="{x: 128, y: 72}">Second</option>
    </select>

Demo

Of course, you should define your model in the code, not in the template. This allows selecting the first element of the array of points by default:

points = [
  {name: 'First', value: {x: 192, y: 108}},
  {name: 'Second', value: {x: 128, y: 72}}
];

point: {x: number; y: number;} = this.points[0].value;

And in the template:

    <select name="point" [(ngModel)]="point">
      <option *ngFor="let p of points" [ngValue]="p.value">{{ p.name }}</option>
    </select>

Demo

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. This works. Unfortunately it does not set the default option visible. Any idea how to make default option displayed. I mean, before you click anything, there should be an option already displayed. At the moment, it is blank.
This indeed works perfectly. But I am even more confused. What I tried was setting pointdirectly point= {x:192, y:108}. This does not make select element display a default value. But if I store the points in an array first, as you did, than it works. Why is that?
Because, in JavaScript, {x:192, y:108} === {x:192, y:108} is false. The selected point must be the exact same object as on of the options. Not a different object having the same properties.
gotcha. Thanks for your time:)

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.