Angular ngClass and click event for toggling class

后端 未结 7 1327
粉色の甜心
粉色の甜心 2020-12-02 18:30

In Angular, I would like to use ngClass and click event to toggle class. I looked through online but some are angular1 and there isn\'t any clear instruction or

7条回答
  •  执笔经年
    2020-12-02 18:39

    Angular6 using the renderer2 without any variables and a clean template:

    template:

    in ts:

    toggleClass(event: any, class: string) {
      const hasClass = event.target.classList.contains(class);
    
      if(hasClass) {
        this.renderer.removeClass(event.target, class);
      } else {
        this.renderer.addClass(event.target, class);
      }
    }
    

    One could put this in a directive too ;)

提交回复
热议问题