Angular ngClass and click event for toggling class

Steve Kim picture Steve Kim · Jun 14, 2017 · Viewed 233.2k times · Source

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 example. Any help will be much appreciated!

In HTML, I have the following:

<div class="my_class" (click)="clickEvent($event)" ngClass="{'active': toggle}">
  Some content
</div>

In .ts:

clickEvent(event) {
  // Haven't really got far
  var targetEle = event.srcElement.attributes.class;
}

Answer

Mani S picture Mani S · Jun 14, 2017

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;       
}