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
2

2 Answers 2

1

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

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

Comments

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.

3 Comments

But since I don't have the possible values in an object or array, how would this work?
<option value="{{false}}">No</option> <option value="{{true}}">Yes</option>, 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: <option value="false">No</option> <option value="true">Yes</option>
That does not seem to work. The values still end up as strings into the model.

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.