How to change an element’s CSS class and remove all other classes on click

后端 未结 4 2025
隐瞒了意图╮
隐瞒了意图╮ 2021-02-03 10:49

How do I handle a case in AngularJS 2 where on click of an element it needs to change its own style, and if other elements have that style they need to have it removed — prefera

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-03 11:16

    The easiest fix to your problem is to assign a unique ID to each included element together with employing another variable to hold selected ID. The logic to turn on my-class CSS class will now be based on the selected ID.

    Your new HTML template:

    > I'm a div that gets styled on click

    Your toggleHighlight function:

    highlightedDiv: number;
    
    toggleHighlight(newValue: number) {
      if (this.highlightedDiv === newValue) {
        this.highlightedDiv = 0;
      }
      else {
        this.highlightedDiv = newValue;
      }
    }
    

    Working Plnk: https://plnkr.co/edit/fNoXWhUhMaUoeMihbGYd?p=preview

提交回复
热议问题