Angular NgClass – How to Add Dynamic Class in Angularjs?

Today, We want to share with you angular add class.In this post we will show you angular class conditional, hear for angular dynamic class we will give you demo and example for implement.In this post, we will learn about AngularJS Added ng class to toggle Active Menu with an example.

Free Live Chat for Any Issue

Angular ngClass and ngStyle: The Complete Guide

Example 1: Simple NgClass

app.component.ts

import { Component } from '@angular/core';
   
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
    isProductAvailable: boolean = true;
   
}

app.component.html

<button 
    [ngClass]="{
        'btn-success': isProductAvailable,
        'btn-primary': !isProductAvailable
    }">
    My Button
</button>

Example 2: Simple class

app.component.ts

import { Component } from '@angular/core';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   
    isProductAvailable: boolean = true;
  
}

app.component.html

<button 
    [class.active] = "isProductAvailable"
    >
    My Button
</button>

Example 3: NgClass with ternary

app.component.ts

import { Component } from '@angular/core';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   
     isProductAvailable: boolean = true;
   
}

app.component.html

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

Example 4: NgClass with Array

app.component.ts

import { Component } from '@angular/core';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
   
    allProductInformation = [
       {
           id: 1,
           title: 'Laptop',
           status: 'active'
       },
       {
           id: 2,
           title: 'Dasktop',
           status: 'pending'
       },
       {
           id: 3,
           title: 'Mobile',
           status: 'expired'
       },
    ]
   
}

app.component.html

<div *ngFor="let item of allProductInformation">
   
    <p [ngClass]="{
      'text-success':item.status === 'active',
      'text-primary':item.status === 'pending',
      'text-danger':item.status === 'expired'
    }">{{ item.title }}
    </p>
   
</div>

I hope you get an idea about Angular NgClass Examples.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Rate this post