Search code examples
angularangular-ng-class

Angular ngClass and click event for toggling class


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

Solution

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