Many times we need to change the look and feel of an element in response to an event. This means that we need to apply dynamic style to an element in angular based on some condition.
Toggling a CSS class means adding and removing the class. This might be on some event such as a click event. This article will explain how to add and remove a CSS class on click.

Toggle class
A class can be toggled using class binding in angular. Syntax to apply class binding is by using class. followed by the name of the class to be applied as shown below.

<div [class.className] = “condition” />

where condition must return true or false. If it returns true, the class will be applied otherwise not.Notice that class.className is enclosed between square brackets. Examples,

<div [class.clicked] = “isClicked()” />

In this example, the class clicked will be applied if the method isClicked in component class will return true.

<div [class.visited] = “isVisited == true” />

In this example, the class visited will be applied if the property isVisited in component class will beĀ true.

Toggle class on click
For toggling class on click event, associate the click event with a function in component class which will reverse the condition of class binding. Example,

<div [class.visited] = “isVisited == true” (click) = “checkVisited()” />

Above example binds a class with the isVisited property of component class. Associate a click event with this div so that when the div is clicked, it will invoke a function in component class.
This function will simply reverse the value of property to which the class is bound. Thus, the function will be defined as

public isVisited = false;
public checkVisited() {
   // reverse the value of property
   this.isVisited = !this.isVisited;

When the component loads, isVisited is set to false so that the div will not contain the class visited. When the div is clicked, the value of isVisited will be set to true.
This means that the condition of class binding(isVisited == true) becomes true and the class is applied.
Now when the div is clicked again, the value of isVisited becomes false and the class is removed.
Thus, we have successfully toggled the class on click event.

Hit the clap below if this article helped you to learn class toggle in angular on click event.

Liked the article ? Spread the word...

Leave a Reply