Fez Vrasta
Fez Vrasta

Reputation: 14815

How to add a class to the selected component?

I have a list of components (all the same)

<ul class="search-results">
  {{#each res as |item|}}
    {{search-result item=item}}
  {{/each}}
</ul>

I'd like to add a class on the clicked element, and, when a new element is clicked, the old element should become "unclicked" (aka, remove the class).

Which is the best way to obtain this result?

Upvotes: 2

Views: 42

Answers (1)

artych
artych

Reputation: 3669

Add activeItem to controller (wrapper component) and send it down to all search-result components. Activate item through sending action activate up.

// template
<ul class="search-results">
  {{#each res as |item|}}
    {{search-result item=item activeItem=activeItem activate="activate"}}
  {{/each}}
</ul>

// controller (wrapper component)
activeItem: null,
actions: {
  activate(item) {
    this.set('activeItem', item);
  }
}

// search-result component
activeItem: null,
isActive: Ember.computed('item', 'activeItem', function() {
  return (this.get('item') === this.get('activeItem'));
}),
click() {
  this.sendAction('activate', this.get('item'));
}

Upvotes: 5

Related Questions