Klaxx
Klaxx

Reputation: 400

How to select the clicked element in a ng for and add class only to the selected element?

I have a list and my last column should be like apples "more options icon", so that a dropdown pops up with additional options.

<tr *ngFor="let foo of bars">
            <td>{{foo.id}}</td>
            <td>{{foo.name}}</td>
            <td class="more-options-menu">
              <i class="icon i-menu" (click)="toggleOptionsMenu()"></i>
              <div id="more-options-{{foo.id}}" [className]="!toggleOptions ? 'more-options-menu-content' : 'more-options-menu-content show-menu'">
                <a href="#">Link 1</a>
                <a href="#">Link 2</a>
                <a href="#">Link 3</a>
              </div>
            </td>
          </tr>

The problem i am having is, that if i click one of the items in the list, the css class "show-menu" is added to all of the listitems, so that the menu is shown on all items and not just the one I clicked. How can I add the class only to the selected item?

I tried using the id "more-options-xx", but I also cant figure out how.

Upvotes: 2

Views: 48

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191819

I would suggest that you keep track of the selected id as a separate property on your component. For example:

selectedId = null;
toggleOptionsMenu(id) {
  this.selectedId = id;
}

In your template:

<i class="icon i-menu" (click)="toggleOptionsMenu(foo.id)"></i>
<div id="more-options-{{foo.id}}" class="more-options-menu-content"
  [class.show-more]="foo.id === selectedId">

Upvotes: 4

Related Questions