Add a class to a selected element within a component


I want to display a modal dialog in my application, which allows the user to manipulate elements of a model. I do not want to use a route for this, as I don’t want to reflect the state if the modal is being displayed within the url.

for instance, if I had a user model, which contains an array of colours:

  'name': 'john',
  'colors': [{name: 'red', count: 1}, {name: 'blue', count: 2}]

In the modal I would like to render the list of colours. Each color within a span. I would like to make the color clickable, and when a color is select I would like to show the details below this list. I am having trouble finding a way to add a class to the span that has been selected.

    {{#each colours as |colour|}}
        <span class="{{if <<How do I find out if this colour is the selected?>>  'selected'}}" {{action "selectColour" colour}}>

So, it would be easy to set the selected Colour within the component. However, I can’t find a way to add a class to the one selected span. I can’t use a computed property to do so, as I can not pass the currently evaluated instance within the each loop to that function. How would one solve something like this in Ember?



I see two possible solutions here:

  1. Copy your whole colours array in an computed property and track the selected state there. (Basically adding a is-selected field to each colour object.
  2. Use a small if helper and check against the selected colour in an sub expression.



Thanks a lot. I didn’t want to add a selected property to the array as it always is kind of cumbersome to clean that up. However your second suggestion looks great to me.