How To Style Components Using Angular ngClass?
Last Updated :
17 Sep, 2024
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
Folder StructureDependencies
"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.
HTML
<!-- src/app/toggle-button/toggle-button.component.html -->
<button (click)="toggle()" [ngClass]="{ 'active': isActive, 'inactive': !isActive }">
{{ isActive ? 'Active' : 'Inactive' }}
</button>
CSS
/* 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;
}
JavaScript
// 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
HTML
<!-- src/app/app.component.html -->
<h1>{{ title }}</h1>
<app-toggle-button></app-toggle-button>
JavaScript
// 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
How to Style Components Using Angular ngClass
Similar Reads
Angular PrimeNG Form Rating Styling Component
Angular PrimeNG is an open-source library that consists of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will Angular PrimeNG Form Rating Styling Component. The Form Rating Component is a s
4 min read
Angular PrimeNG Form Knob Styling Component
Angular PrimeNG is a collection of UI components made for Angular applications. It makes it easy for developers to build beautiful and efficient web interfaces without investing much time. In this article, we will be seeing the Angular PrimeNG Form Knob Styling Component. The Knob Component is used
4 min read
Angular PrimeNG Form Dropdown Styling Component
Angular PrimeNG is an open-source front-end UI framework developed by PrimeTek for developing efficient and scalable angular applications. Using PrimeNG in their projects helps developers to cut down the development time and focus on other important areas of the application. In this article, we will
5 min read
Angular PrimeNG Form InputMask Styling Component
Angular PrimeNG is a collection of Angular UI components. It is an open-source library developed by PrimeTek. It has many ready-to-use components that make it one of the top choices of angular developers when it comes to choosing a UI library. In this article, we will see the Angular PrimeNG Form In
4 min read
Angular PrimeNG Form Editor Styling Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see Angular PrimeNG Form Editor Styling Component. The Form Editor is a Qui
3 min read
Angular PrimeNG StyleClass Component
Angular PrimeNG is an open-source framework for Angular applications. It has a rich set of native UI components that can be used to make attractive and scalable web interfaces. In this article, we will see Angular PrimeNG StyleClass Component. StyleClass is used to manage CSS classes during entering
4 min read
Angular PrimeNG Form Password Styling Component
Angular PrimeNG is an open-source front-end UI framework developed by PrimeTek for developing efficient and scalable angular applications. Using PrimeNG in their projects helps developers to cut down the development time and focus on other important areas of the application. In this article, we will
4 min read
Angular PrimeNG Form Chips Styling Component
Angular PrimeNG is a front-end UI component library for Angular Applications. It is developed and maintained by PrimeTek. PrimeNG helps developers to create stunning web interfaces in less time using pre-built components and themes. In this article, we will discuss the Angular PrimeNG Form Chips Sty
3 min read
Angular PrimeNG FloatLabel Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the FloatLabel component in angular PrimeNG. FloatLabel com
2 min read
Angular PrimeNG Form MultiSelect Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will learn how to use the MultiSelect Component in Angular PrimeNG. The Multisel
9 min read