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

后端 未结 4 2027
隐瞒了意图╮
隐瞒了意图╮ 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:19

    One solution which worked for me in showing the active menu is using typescript variable name in class as in

    `class="{{ text1Class }}"`  
    

    and assign the class name in typescript.

    `this.text1Class = "active";` 
    

    or

    `this.text1Class = "inactive";`
    

    You need to have different style class like this

    `.inactive {
     background-color : gray;
     padding : 10px;
    }
    .active {
      background-color : green;
      padding : 10px;
    }`
    

    Assign the class name inside the function

    `textOneClicked() : void {
    this.text1Class = "active"; // set the active class
    this.text2Class = this.text3Class = this.text4Class = "inactive"; // reset other classes
    

    }`

    A working Plunker here

提交回复
热议问题