Tutorial – 10 – Class Binding

Class binding


You can add and remove CSS class names from an element’s class attribute with a class binding.[class.class-name].

<div class="alert alert-success">
 <strong>Success!</strong> This alert box could indicate a successful or positive action.
</div>

output

Success! This alert box could indicate a successful or positive action.
export class AppComponent {
    successClass="alert-success";
}
<div [class]="successClass">
  <strong>Success!</strong> This alert box could indicate a successful or positive action.
</div>
Success! This alert box could indicate a successful or positive action.

If we use class and [class] binding at a time ?

export class AppComponent {
    successClass="alert-success";
}
<div [class]="successClass" class="alert">
  <strong>Success!</strong> This alert box could indicate a successful or positive action.
</div>

output

Success! This alert box could indicate a successful or positive action.
The class property is behave like a dummy property.Use either one not both.

Another Syntax based on Expression or Conditions

export class AppComponent {
     successClass="alert-success";
     hasError = true;
}
<div [class.alert-danger]="hasError">
   <strong>Danger!</strong> This alert box could indicate a dangerous or potentially negative action.
</div>

output

Danger! This alert box could indicate a dangerous or potentially negative action.

Alternate Syntax for Class Binding is [NgClass]

NgClass directive is usually preferred when managing multiple class names at the same time.

export class AppComponent {
    successClass={
          "alert-success",
          "alert-warning"
    };
}
<div [ngClass]="successClass" class="alert">
  <strong>Success!</strong> This alert box could indicate a successful or positive action.
</div>

output

Success! This alert box could indicate a successful or positive action.

Leave a Reply

Your email address will not be published. Required fields are marked *