0

I'm creating a <select> dropdown using HTML5 and angular. I need the selected <option> to be determined dynamically via angular. If this were to be a static dropdown, it could be done as such:

<select>
  <option value="1" selected>1</option>
  <option value="2">2</option>
</select>

A typical dynamic value could be determined as such (assuming val1 and val2 are declared in the component):

<select>
  <option [value]="val1">1</option>
  <option [value]="val2">2</option>
</select>

But given that the select attribute has no ="" at the end, how could one assign it dynamically? In general, how could one assign such a value in angular? Especially since even if a value is provided to selected, it's simply ignored. So for example, <option selected="false"> would be rendered the same as <option selected>.

1 Answer 1

2

I eventually figured this one out on my own. The answer turns out to be pretty simple.

(assume that value is declared in the component)

<select>
  <option value="1" [selected]="value == 1">1</option>
  <option value="2" [selected]="value == 2">2</option>
</select>

I didn't think this would work, since in plain HTML selected="false" would still render the same as selected. However, it makes sense if you think about it. Adding the [] brackets tells angular to compute the value at compile time. And if the value is falesy, it will simply never make it into the DOM! So from HTML's perspective, <option value="myValue" [selected]="false"> will translate as <option value="myValue">.

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

Comments

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.