Skip to main content

ngClass

ngClass is a built-in directive in Angular that allows you to dynamically add or remove CSS classes to an HTML element based on an expression. This directive is particularly useful for changing the appearance of elements in response to component state or user interactions.

How ngClass Works

ngClass can be used in several ways, depending on the complexity of the conditions and the number of classes you need to manipulate. It evaluates the given expression and, based on its result, adds or removes CSS classes.

Basic Usage

  1. Single Class Toggle: You can toggle a single class based on a truthy or falsy expression.

    <div [ngClass]="{'active': isActive}">Content</div>

    Here, the active class is added to the <div> if isActive is truthy.

  2. Multiple Classes: You can toggle multiple classes using a similar object syntax.

    <div [ngClass]="{'active': isActive, 'disabled': isDisabled}">Content</div>

    This adds the active class if isActive is true and the disabled class if isDisabled is true.

Advanced Usage

  1. Array Syntax: You can pass an array of class names, which will all be applied.

    <div [ngClass]="[class1, class2, class3]">Content</div>

    Here, class1, class2, and class3 are all added to the <div>.

  2. Class with Conditional Logic: Using a function or a component property, you can return an object or array to ngClass.

    <div [ngClass]="getClassObject()">Content</div>

    In the component:

    getClassObject() {
    return {
    'class1': this.condition1,
    'class2': this.condition2,
    // more classes and conditions
    };
    }

    The function returns an object with class names as keys and conditionals as values.

Combining with Static Classes

  • ngClass can be used alongside static class attributes. The static classes will always be applied, and the dynamic classes will be added or removed based on the ngClass expression.

    <div class="static-class" [ngClass]="{'dynamic-class': condition}">Content</div>

More examples

Here are more examples to illustrate its different applications:

Toggling Multiple Classes with an Object

  1. Object Syntax for Multiple Conditions: Toggle multiple classes based on different conditions.

    <div [ngClass]="{ 'class1': condition1, 'class2': condition2, 'class3': condition3 }">
    Content
    </div>

    This adds class1 if condition1 is true, class2 if condition2 is true, and so on.

Using Component Properties

  1. Based on Component Properties: Dynamically apply classes based on component property values.

    <div [ngClass]="{ 'highlight': isHighlighted, 'shadow': hasShadow }">
    Content
    </div>

    Here, isHighlighted and hasShadow are boolean properties in the component. The respective classes are applied based on their truthiness.

With Array Syntax

  1. Array Syntax with Conditional Classes: Apply an array of classes, some of which are conditional.

    <div [ngClass]="[ alwaysClass, condition ? 'conditionalClass' : '' ]">
    Content
    </div>

    alwaysClass is always applied, while conditionalClass is applied only if condition is true.

Combining Static and Dynamic Classes

  1. Static and Dynamic Classes Together: Use ngClass alongside static class attributes.

    <div class="static-class" [ngClass]="{ 'dynamic-class': condition }">
    Content
    </div>

    The element always has static-class, and dynamic-class is added based on condition.

Function Return Values

  1. Using a Function to Determine Classes: Define a method in the component to return the classes.

    <div [ngClass]="getClass()">Content</div>

    In the component:

    getClass() {
    return {
    'class1': this.condition1,
    'class2': this.condition2,
    // ... more logic
    };
    }

    This method returns an object with class names as keys and conditions as values.

Responsive Design

  1. Responsive Styling: Apply different classes based on screen size or other environmental factors.

    <div [ngClass]="{ 'mobile-class': isMobile, 'desktop-class': !isMobile }">
    Content
    </div>

    This applies mobile-class if isMobile is true (which could be determined by screen width), and desktop-class otherwise.

Form Validation Feedback

  1. Form Validation Styles: Change styles based on the validation state of form controls.

    <input [ngClass]="{ 'valid': myControl.valid, 'invalid': myControl.invalid }" type="text" formControlName="myControl">

    This applies valid or invalid classes based on the control's validation status.

Dynamic Theme Application

  1. Dynamic Theming: Apply a theme class based on a user's preference or setting.

    <div [ngClass]="currentTheme">Content</div>

    currentTheme is a string property in the component that holds the name of the CSS class representing the theme.

Toggle Classes with User Interaction

  1. Toggling Classes on Events: Change classes in response to user actions like click, hover, etc.

    <div (click)="toggleClass = !toggleClass" [ngClass]="{ 'active': toggleClass }">
    Click me
    </div>

    Toggles the active class on click.

Use Cases

  • Styling Based on Component State: Changing the appearance of elements based on the state of the component (e.g., active/inactive states, validation states in forms).
  • Responsive Design: Applying different styles based on screen size or other environmental factors.
  • User Interactions: Changing styles in response to user actions like hover, click, etc.

Best Practices

  • Keep It Simple: Avoid overly complex expressions in ngClass. If the logic gets complicated, consider moving it to the component class.
  • Performance Considerations: Be mindful of performance, especially when using functions or methods that return class objects or arrays, as they can be called frequently.

Conclusion

ngClass is a powerful and flexible directive for dynamically manipulating CSS classes of elements in Angular applications. It enhances the ability to create responsive and interactive user interfaces by binding element class attributes to component logic. Understanding ngClass and its various usage patterns is essential for effective Angular development.