×
☰ See All Chapters

Angular ngClass Directive

ngClass directive allows us to add or remove CSS classes to an HTML element. Using ngClass we can create dynamic styles in HTML pages.

Angular ngClass Directive Example

app.component.ts

import { Component } from '@angular/core';

 

@Component({

        selector: 'app-tag',

        template: ` <div [ngClass]="'red'">

                        Red Text with Bold

                    </div>

                    `,

        styles: ['.red { font-weight: bold; color: red;}']

})

export class AppComponent {

        num: string='';

}

 

app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

 

@NgModule({

  declarations: [

      AppComponent

  ],

  imports: [

    BrowserModule

  ],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

index.html

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>Angular Example</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

</head>

<body>

  <app-tag></app-tag>

</body>

</html>

Output

angular-ngclass-directive-0
 

Inside a template element, NgClass can be assigned to one of three types of values:

1. string

2. array

3. object

ngClass Binding to a String

<div [ngClass]="'red size20'">

    Red Text with Size 20px

</div>

We can also use the ngClass without a square bracket. In that case, the expression is not evaluated but assigned directly to the class attribute. We also need to remove the double quote around the expression as shown below.

<div class="row">

    <div ngClass='red size20'>

        Red Text with Size 20px : as string

    </div>

</div>

ngClass Binding to an array

<div [ngClass]="['red','size20']">

    Red Text with Size 20px

</div>

ngClass Binding to an object

<div class="row">

    <div [ngClass]="{'red':true,'size20':true}">

       Red Text with Size 20px : as object

    </div>

</div>

 


All Chapters
Author