Angular 16 dynamically add and remove classes; Through this tutorial, i am going to show you how to add and remove classes in Angular 16 apps.
Angular 16 dynamically add and remove CSS Classes using ngClass and custom directive
Follow the below given steps to dynamically add and remove css classes using ngClass and custom directive in Angular 16 apps:
- Angular dynamically add and remove CSS Classes using Simple Class
- Angular dynamically add and remove CSS Classes using ngClass
- Angular dynamically add and remove CSS Classes using NgClass with ternary
Angular dynamically add and remove CSS Classes using Simple Class
Step 1 – Import Module
Go to src directory and open app.component.ts and add following code into it:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { isFavorite: boolean = true; }
Step 2 – Add Code on View File
Go to src/app/app.component.html and add the following code into it:
<button [class.active] = "isFavorite" > My Button </button>
Angular dynamically add and remove CSS Classes using ngClass
Step 1 – Import Module
Go to src directory and open app.component.ts and add following code into it:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { isFavorite: boolean = true; }
Step 2 – Add Code on View File
Go to src/app/app.component.html and add the following code into it:
<button [ngClass]="{ 'btn-success': isFavorite, 'btn-primary': !isFavorite }"> My Button </button>
Angular dynamically add and remove CSS Classes using NgClass with ternary
Step 1 – Import Module
Go to src directory and open app.component.ts and add following code into it:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { isFavorite: boolean = true; }
Step 2 – Add Code on View File
Go to src/app/app.component.html and add the following code into it:
<button [ngClass]="[ isFavorite ? 'btn-success' : 'btn-danger']" > My Button </button>
Start Angular App
Run the following command on command prompt to start angular app:
ng serve