Back to all posts

Dynamic Styling in Angular


Two key methods for dynamic styling in Angular: the ngClass directive and inline styles using the style attribute.

Using ngClass Directive

1. Basic Object Syntax:

You can bind an object to the ngClass directive where keys are class names and values are boolean expressions that determine if the class should be applied.

<div [ngClass]="{'highlight': isActive, 'large': true}">Dynamic Classes</div>

2. Array Syntax:

You can also pass an array of class names to ngClass. This allows you to combine multiple classes conditionally.

<button [ngClass]="[isFavorite ? 'btn-success' : 'btn-danger']">My Button</button>

3.Multiple Classes:

You can define multiple classes using an object literal or an array of strings.

<div [ngClass]="{'active': isActive, 'admin': isAdmin, 'subscriber': !isAdmin}"></div>

Using Property Binding

1 Direct Class Binding:

You can use property binding to toggle a single class based on a condition.

<div class="list" [class.active]="isActive"></div>

    2 Using Ternary Operators:

    You can also use ternary operators directly within the binding for more concise logic.

    <button [class]="isFavorite ? 'btn-success' : 'btn-primary'">My Button</button>

    Using HostBinding:

    If you want to add a class to the host element of a component, you can use Angular’s @HostBinding.

    import { Component, HostBinding } from '@angular/core';
    
    @Component({
      selector: 'app-my-component',
      template: `<p>Content here</p>`
    })
    export class MyComponent {
      @HostBinding('class.active') isActive = true;
    }