Ng Class and Ng Style in Angular

In this article, we will figure out how to use ngStyle and ngClass in angular

Using this article, you can easily understand how to work ngStyle and ngClass. The ngStyle attribute is used to change or style the multiple properties of Angular. You can change the value, color, and size, etc. of the elements.

So let’s See below example here,

Step 1:-

In your Angular Application Add the following Command in your app.component.ts file

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  
  serverStatus: string = 'Online';  
  
  constructor () {}  
  online(){
    this.serverStatus = 'Online';  
  }
  offline(){
    this.serverStatus = 'Offline';  
  }
  getServerStatus() {  
    return this.serverStatus;  
  }  
  getColor() {  
    return this.serverStatus === 'Online' ? 'green' : 'red';  
  } 

}

Step 2:-

Add the following Command in your app.component.html file

<div class="btnclass">
    <button class="btn btn-success" (click)="online()">Online</button> &nbsp;&nbsp;&nbsp;
    <button class="btn btn-danger" (click)="offline()">Offline</button>
</div>

<p [ngStyle]="{backgroundColor: getColor()}"> Hello , your status is {{serverStatus}} </p>
<p [ngClass]="serverStatus === 'Online' ? 'Online' : 'Offline' "> Hello , your status is {{serverStatus}} </p>

Using ngClsss and ngStyle you can change, Add, or Remove CSS dynamically.

Step 3:-

Add the following command in your app.component.scss file

.btnclass{
    padding: 10px;
}
.Online{  
    color: rgb(23, 82, 26);  
}
.Offline{
    color: rgb(250, 15, 15); 
}

Step 4:-

Run Angular Application

npm start

Output:-

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories