How to style components using Angular ngClass
The ngClass is a built-in Angular directive used to style a component based on its state or user interaction. It lets us play around with CSS classes by adding or removing them directly on HTML elements.
To begin, we must import CommonModule initially. To do so, open the app.module.ts file and add the following piece of code.
import { CommonModule } from '@angular/common';// Other imports@NgModule({imports: [CommonModule,// Other imports],// Other module configuration})export class AppModule { }
There are three basic ways to apply the ngClass directive:
Using an object literal
Using an expression
Using an object
Using an object literal
We can pass an object literal to the ngClass directive. Here, the key is a class, which is applied to the component if the value is true. In the below example, we’re styling the message declared in the app.component.ts file (line 9).
Look at the app.component.css file.
Lines 17–19: We have defined the styles for the
successclass. It setsgreenas the background color.
Look at the app.component.html file.
Line 1: Through the directive, the
successclass will be applied to complete<div>element as its value istrue.
Note: Try changing the value to
falsein theapp.component.htmlfile and notice the result.
Using an expression
The directive becomes more useful when the value is dynamic (based on user interaction). Here, the value can be computed through a JavaScript expression. In the example below, we’re styling the message declared in the app.component.ts file (line 9).
Look at the app.component.css file.
Lines 17–19: We have defined the styles for the
successclass. It setsgreenas the background color.Lines 21–23: We have defined the styles for the
errorclass. It setsredas the background color.
Look at the app.component.html file.
Line 1: Through the directive, the
successclass will be applied to complete<div>element only if themessageis‘Hello world’. Otherwise, theerrorclass will be applied.
Note: Try changing the
messagevalue in theapp.component.tsfile and notice the result.
Using an object
We can also bind the ngClass directive to an object created inside a component. It becomes readable and thus easy to understand, and modify the code. In the example below, we’re styling the message declared in the app.component.ts file (line 9).
Look at the app.component.css file.
Lines 17–19: We have defined the styles for the
successclass. It setsgreenas the background color.Lines 21–23: We have defined the styles for the
weightclass. It bolds the text.
Look at the app.component.ts file.
Lines 11–14: We have created a
styleobject and set all the classes totrue(as discussed above).
Look at the app.component.html file.
Line 1: Through the directive, the
styleobject will be applied to complete<div>element.
Note: Try changing the values of classes in the
app.component.tsfile and notice the result.
Free Resources