Skip to content Skip to sidebar Skip to footer

Toggleclass() Not Working In Angular 4

I've added jQuery in script and used import * as $ from 'jquery'; as well. I've also added jQuery in the HTML file. But my toggleClass() function is not working. When I chec

Solution 1:

You don't need to use jquery, just change your click binding on view to (click)="myFunc($event)", and on myFunc change to:

myFunc(e) {
    consttarget: HTMLElement = e.target;
    target.classList.toggle('active');
}

Solution 2:

It may not be working because $(this) is referring to the current class instance.

you need to refer the source element in the jquery to work properly. Pass '$event' object to your function from the template and get the target object inside the function:

<div class="web" (click) = "myFunc($event)">

myFunc(event: any) {
  $(event.target).toggleClass("active");
}

See this stackblitz: https://stackblitz.com/edit/angular-dsely1

Post a Comment for "Toggleclass() Not Working In Angular 4"