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
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 success
class. It sets green
as the background color.
Look at the app.component.html
file.
Line 1: Through the directive, the success
class will be applied to complete <div>
element as its value is true
.
Note: Try changing the value to
false
in theapp.component.html
file and notice the result.
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 success
class. It sets green
as the background color.
Lines 21–23: We have defined the styles for the error
class. It sets red
as the background color.
Look at the app.component.html
file.
Line 1: Through the directive, the success
class will be applied to complete <div>
element only if the message
is ‘Hello world’
. Otherwise, the error
class will be applied.
Note: Try changing the
message
value in theapp.component.ts
file and notice the result.
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 success
class. It sets green
as the background color.
Lines 21–23: We have defined the styles for the weight
class. It bolds the text.
Look at the app.component.ts
file.
Lines 11–14: We have created a style
object and set all the classes to true
(as discussed above).
Look at the app.component.html
file.
Line 1: Through the directive, the style
object will be applied to complete <div>
element.
Note: Try changing the values of classes in the
app.component.ts
file and notice the result.
Free Resources