Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; } 
like image 369
Steve Kim Avatar asked Jun 14 '17 04:06

Steve Kim


People also ask

Can we use ngClass with class?

yes , you can do it.

Can we use ngClass and NgStyle together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.


2 Answers

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;        } 
like image 56
Mani S Avatar answered Sep 26 '22 13:09

Mani S


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-

component.html -

<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.
EDIT: Recent versions of angular require the variable to be declared in the controller - component.ts -

status: boolean = false; 
like image 32
charsi Avatar answered Sep 23 '22 13:09

charsi