【问题标题】:How to select the clicked element in a ng for and add class only to the selected element?如何在 ng for 中选择单击的元素并将类仅添加到所选元素?
【发布时间】:2019-03-07 15:42:35
【问题描述】:

我有一个列表,我的最后一列应该像苹果"more options icon",这样会弹出一个带有其他选项的下拉列表。

<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>

我遇到的问题是,如果我单击列表中的一项,css 类“show-menu”会添加到所有列表项中,以便菜单显示在所有项目上,而不仅仅是我点击的那个。如何仅将课程添加到所选项目?

我尝试使用 id “more-options-xx”,但我也不知道如何使用。

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    我建议您将所选 id 作为组件上的单独属性进行跟踪。例如:

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

    在您的模板中:

    <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">
    

    【讨论】:

    • 不错!有用!感谢你及时的答复。我只需要找到一种在第二次单击时关闭菜单的方法。
    • toggleOptionsMenu(id) { if (this.selectedId === id) { this.selectedId = null; } 其他 { this.selectedId = id; } } - 知道了!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2014-06-28
    • 1970-01-01
    • 2017-04-15
    相关资源
    最近更新 更多