Class binding can be used to set a class property of an element. there are multiple ways to bind the class to the element.
Single class binding based on the boolean condition
in below syntax class “myClass” will be apply only when “myTsVariable” variable is true in ts file.
[class.myClass]="myTsVariable"
How to apply multiple classes in angular using Multi-class binding
In below example you can assign multiple class name to my class variable with space between class name
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <h2> Welcome {{name}} </h2> <h2 [class]="myClass" > Class Binding </h2> `, styles: [` .text-danger { color: red; } .text-success { color: green; } .text-italic { font-style: italic; } `] }) export class TestComponent implements OnInit { public name = "Amey Raut"; public myClass = "text-success text-italic" constructor() { } ngOnInit() { } }
How to apply multiple class-based on condition, using ngClass Directive
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <h2 [ngClass]="myClasses" > Class Binding </h2> `, styles: [` .text-danger { color: red; } .text-success { color: green; } .text-italic { font-style: italic; } `] }) export class TestComponent implements OnInit { public applyDangerClass = true; public applyItalic = true; public myClasses = { "text-danger": this.applyDangerClass, "text-success": !this.applyDangerClass, "text-italic": this.applyItalic } constructor() { } ngOnInit() { } }
How to add a condition in HTML/template file to toggle CSS class – Angular class binding using ternary operator
In the below example, if the variable “applyDangerClass” is true then “text-danger” class will be applied if it is false the “text-success” will be applied.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <h2> Welcome {{name}} </h2> <h2 [class]="applyDangerClass ? 'text-danger' : 'text-success' " > Class Binding </h2> `, styles: [` .text-danger { color: red; } .text-success { color: green; } `] }) export class TestComponent implements OnInit { public name = "Amey Raut"; public applyDangerClass = true; constructor() { } ngOnInit() { } }