Angular ngClass and click event for toggling class Angular ngClass and click event for toggling class angular angular

Angular ngClass and click event for toggling class


This should work for you.

In .html:

<div class="my_class" (click)="clickEvent()"      [ngClass]="status ? 'success' : 'danger'">                     Some content</div>

In .ts:

status: boolean = false;clickEvent(){    this.status = !this.status;       }


Instead of having to create a function in the ts file you can toggle a variable from the template itself. You can then use the variable to apply a specific class to the element. Like so-

<div (click)="status=!status"      [ngClass]="status ? 'success' : 'danger'">                     Some content</div>

So when status is true the class success is applied. When it is false danger class is applied.

This will work without any additional code in the ts file.


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

template:

<div (click)="toggleClass($event,'testClass')"></div>

in ts:

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

One could put this in a directive too ;)