Wednesday 26 February 2020

Conditionally add class using ngClass angular


In this article we will be discussing about adding css class dynamically using angular [ngClass]. One of my previous articles I wrote about different ways of adding class dynamically.

Let us check what are the different ways we can add a class using ngClass.

1. Add single class
2. Add multiple class
3. Multiple conditions
4. Using shared or common service

Conditionally add class using Angular - 5 methods
Conditionally add class to an element on click - angular

1. Add single class

<p [ngClass]="{'active-class': status === 'read'}">Demo text</p>

Here class will get added if the conditions is true. Same you can add in a method and use as well.

<!--boolean -->
<p [ngClass]="{'active-class': isRead}">Demo text</p>

<!--using method -->
<p [ngClass]="{'active-class': isStatus()}">Demo text</p>

// example
public isRead: boolean = true;

public isStatus(): boolean {
    return true;

2. Add multiple classes

Similar way you can add multiple classes as well, check below examples.

<p [ngClass]="{'active-class1, active-class2': isStatus()}">Demo text</p>

3. Multiple conditions

Here we will be adding multiple classes using different conditions

<p [ngClass]="{'active-class1': status === 'read', 'read-class': isStatus()}">
  Demo text</p>

4. Using shared or common service

Create a shared service or a common service and declare your Boolean variable there. For example

<p [ngClass]="{'active-class1': commonService.readonlyStatus}">
  Demo text</p>

Simple service file

import {Injectable} from '@angular/core';

  providedIn: 'root'
export class CommonService {

  public readonlyStatus: boolean;

  constructor() {

Now import this service in your components where ever it is required and use this condition as below.

constructor(public commonService: CommonService) {

  public setValue(): void {
    this.commonService.readonlyStatus = true; // or false

Advantage of using like this way, you can reset the variable in any component by importing this service file.

In this article we have discussed about adding class dynamically using angular ngClasss

Related Info

1. How to solve JavaScript heap out of memory issue in Angular project

2. Truncate file name without hiding the extension using Angular Pipe.

3. How to create and use shared module in angular application.

No comments :

Post a Comment