How To Style Components Using Angular ngClass?
Styling components effectively is important in web development, and Angular offers various ways to apply CSS to your components. One of the most powerful and flexible methods is using the ngClass directive.
The ngClass directive allows you to dynamically add or remove CSS classes based on component properties or application state, providing a reactive way to manage styles in your Angular application. In this article, we will cover how to use ngClass to style components in Angular.
How Does ngClass Work?
ngClass evaluates an expression specifying the classes to be added or removed from the target element. The expression can be:
- A string representing a single class or multiple classes.
- An array of class names.
- An object where keys are class names and values are boolean expressions that determine whether the class is applied.
Basic Usage of ngClass
Using ngClass is simple. It is used as an attribute directive on an HTML element, and its value is bound to a class expression.
Example: Basic ngClass Usage
import { Component } from '@angular/core';
@Component({
selector: 'app-basic-ngclass',
template: `
<button [ngClass]="{'btn-primary': isPrimary, 'btn-secondary': !isPrimary}">
Click Me
</button>
<button (click)="toggleClass()">Toggle Class</button>
`,
styles: [`
.btn-primary { background-color: blue; color: white; }
.btn-secondary { background-color: gray; color: white; }
`]
})
export class BasicNgClassComponent {
isPrimary = true;
toggleClass() {
this.isPrimary = !this.isPrimary;
}
}
In this example:
- The ngClass directive is used to conditionally apply either the .btn-primary or .btn-secondary class based on the value of the isPrimary property.
- A button click toggles the isPrimary property, which in turn toggles the class applied to the first button.
Applying Multiple Classes with ngClass
ngClass can also apply multiple classes simultaneously by using arrays or space-separated strings.
Example: Applying Multiple Classes
<div [ngClass]="['class-one', 'class-two']">
This div has multiple classes.
</div>
This binds both class-one and class-two to the <div> element.
Alternatively, you can use a space-separated string:
<div [ngClass]="'class-one class-two'">
This div also has multiple classes.
</div>
Conditional Styling with ngClass
ngClass allows for conditional styling by using objects where each key is a class name and each value is a boolean that determines whether the class should be applied.
Example: Conditional Styling
import { Component } from '@angular/core';
@Component({
selector: 'app-conditional-ngclass',
template: `
<div [ngClass]="{'active': isActive, 'inactive': !isActive}">
This div is {{ isActive ? 'Active' : 'Inactive' }}.
</div>
<button (click)="toggleActive()">Toggle Active</button>
`,
styles: [`
.active { background-color: green; color: white; }
.inactive { background-color: red; color: white; }
`]
})
export class ConditionalNgClassComponent {
isActive = false;
toggleActive() {
this.isActive = !this.isActive;
}
}
The ngClass directive conditionally applies the .active or .inactive class based on the isActive boolean value.
Using ngClass with Arrays and Objects
ngClass can take arrays and objects to handle complex styling scenarios:
Example: Using Arrays and Objects
import { Component } from '@angular/core';
@Component({
selector: 'app-array-object-ngclass',
template: `
<div [ngClass]="currentClasses">
Dynamic classes with array and object.
</div>
`,
styles: [`
.bordered { border: 2px solid black; }
.padded { padding: 20px; }
.highlight { background-color: yellow; }
`]
})
export class ArrayObjectNgClassComponent {
isBordered = true;
isPadded = false;
isHighlighted = true;
get currentClasses() {
return {
'bordered': this.isBordered,
'padded': this.isPadded,
'highlight': this.isHighlighted
};
}
}
The currentClasses object dynamically applies styles based on component state.
Combining ngClass with Angular Expressions
You can combine ngClass with Angular expressions for dynamic class handling.
Example: Combining with Expressions
import { Component } from '@angular/core';
@Component({
selector: 'app-expression-ngclass',
template: `
<div [ngClass]="{'highlight': isHighlighted && hasFocus}">
Highlighted when both conditions are true.
</div>
`,
styles: [`
.highlight { background-color: yellow; }
`]
})
export class ExpressionNgClassComponent {
isHighlighted = true;
hasFocus = true;
}
The class highlight is applied only when both isHighlighted and hasFocus are true.
Steps To Style Components Using Angular ngClass
Step 1: Install Angular CLI and Create a New Project:
If you haven't already, install Angular CLI and create a new Angular project:
npm install -g @angular/cling new my-angular-applicationcd my-angular-application
Step 2: Generate a New Component
ng generate component toggle-button
Folder Structure
Dependencies
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Step 3: Create standalone component that uses ngClass to apply styles conditionally.
<!-- src/app/toggle-button/toggle-button.component.html -->
<button (click)="toggle()" [ngClass]="{ 'active': isActive, 'inactive': !isActive }">
{{ isActive ? 'Active' : 'Inactive' }}
</button>
/* src/app/toggle-button/toggle-button.component.css */
button {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
color: white;
font-size: 16px;
}
/* Styles for active state */
.active {
background-color: #28a745;
}
/* Styles for inactive state */
.inactive {
background-color: #dc3545;
}
// src/app/toggle-button/toggle-button.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-toggle-button',
standalone: true,
imports: [CommonModule],
templateUrl: './toggle-button.component.html',
styleUrls: ['./toggle-button.component.css'],
})
export class ToggleButtonComponent {
// Property to track the toggle state
isActive = false;
// Method to toggle the state
toggle() {
this.isActive = !this.isActive;
}
}
Step 4: Add the component into App component
<!-- src/app/app.component.html -->
<h1>{{ title }}</h1>
<app-toggle-button></app-toggle-button>
// src/app/app.component.ts
import { Component } from '@angular/core';
import { ToggleButtonComponent } from './toggle-button/toggle-button.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [ToggleButtonComponent],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'Angular ngClass Example';
}
To start the application run the following command.
ng serve --open
Output
