2

In Angular2, is there a clean way to handle a form control's value as something else than a string, for example have a <select> with options (bool) true and (bool) false?

Currently I'm using solutions that don't feel very elegant:

<select (change)="model.published = !!$event.target.value">
    <option value="">No</option>
    <option value="1">Yes</option>
</select>

<select (change)="model.type = $event.target.value * 1">
    <option value="1">My value is (int) 1</option>
    <option value="2">My value is (int) 2</option>
</select>

I'm using <select>s in my example, but I'm interested in other form controls as well.

This question was suggested as a duplicate, but I'm don't think it is one since I'm not

  1. interested only in selects
  2. trying to generate options dynamically
Community
  • 1
  • 1
Schlaus
  • 18,144
  • 10
  • 36
  • 64
  • Possible duplicate of [How to use select/option/NgFor on an array of objects in Angular2](http://stackoverflow.com/questions/33181936/how-to-use-select-option-ngfor-on-an-array-of-objects-in-angular2) – Günter Zöchbauer Jan 15 '16 at 09:25
  • Good question, I have exactly the same problem.. Your solution is the best I have found so far, but I agree that it isn't very elegant.. Did you find a solution? – Maarten Kieft May 16 '16 at 12:40

2 Answers2

1

This is a known limitation in the current Angular version https://github.com/angular/angular/issues/2551

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

Yea just add [(ngModel)]="model.published" to the select and it'll set the value property of the <option> selected, if you add an object in the <option> like this: <option value="{{object}}"> you'll set an object, it doesn't have to be a string.

Langley
  • 5,326
  • 2
  • 26
  • 42
  • But since I don't have the possible values in an object or array, how would this work? – Schlaus Jan 15 '16 at 09:37
  • `` ``, but for booleans I dont think you have to use {{}} they should convert if you bind the select to a boolean property by just using: `` `` – Langley Jan 15 '16 at 09:40
  • 1
    That does not seem to work. The values still end up as strings into the model. – Schlaus Jan 15 '16 at 09:50