Angular [class.active]="isActive" - what does "class.active" mean here?

Viewed 15548

In a training video of angular, I saw some codes, like these below:

<button class="nav nav-primary" [class.active]="isActive">

and in the component, If we let the variable isActive=true,then the button has the "active" class;if let the variable isActive=false,then the button has not the "active" class.

I know that this is a one-way binding, but I want to know what's the grammar mean of "class.active"? (the "class" has a property of"active"? but this is impossible.

2 Answers

That means .active state of the current class(style) of the element is run When isActive is true.

According to your code,

In .html File,

<button class="nav nav-primary" [class.active]="isActive">

In .ts File,

public isActive:boolean = true;

I defined 'isActive' as True (default), you can change as you wish ;)

In .CSS File,

.nav-primary {
              color : "Black";
}

.nav-primary.active {
             color : "white";
}

now you can see the colour is white when isActive is True and the colour is Black when isActive is False

It means that you are setting the class with name active (class.active) to that element, if the expression, in this case isActive property is true or can be parsed to true.

Don't think about it as a property active of the class. It just a construct which will be evaluated by Angular to get the name of the class.

From the Documentation

You can bind to a specific class name. Angular adds the class when the template expression evaluates to truthy. It removes the class when the expression is falsy.

Related