What is Class Binding in Angular: Simple Explanation and Example
class binding is a way to add or remove CSS classes on an HTML element dynamically based on component data. It uses the syntax [class.class-name] to toggle classes easily in the template.How It Works
Class binding in Angular works like a light switch for CSS classes on HTML elements. Imagine you have a room with a lamp, and you want to turn the lamp on or off depending on whether it is dark or bright outside. Similarly, Angular lets you turn CSS classes on or off depending on your component's data.
When you use [class.class-name], Angular checks the value you give it. If the value is true, Angular adds the CSS class to the element. If false, it removes the class. This way, your page style can change automatically without you writing extra JavaScript to manipulate classes.
Example
This example shows how to toggle a CSS class called highlight on a paragraph based on a component property.
import { Component } from '@angular/core'; @Component({ selector: 'app-class-binding', template: ` <p [class.highlight]="isHighlighted">This text can be highlighted.</p> <button (click)="toggleHighlight()">Toggle Highlight</button> `, styles: [ `.highlight { color: red; font-weight: bold; }` ] }) export class ClassBindingComponent { isHighlighted = false; toggleHighlight() { this.isHighlighted = !this.isHighlighted; } }
When to Use
Use class binding when you want to change the look of elements based on user actions or data changes without reloading the page. For example, you can highlight a selected item in a list, show error styles on invalid inputs, or toggle visibility styles.
This approach keeps your HTML clean and your styles easy to manage, as you only toggle classes instead of changing styles directly.
Key Points
- Class binding uses
[class.class-name]syntax to toggle CSS classes. - It adds the class when the expression is true and removes it when false.
- It helps keep templates clean and styles consistent.
- Works well for dynamic styling based on component data.
Key Takeaways
[class.class-name] syntax.