Angular 2 NgClass Example

NgClass

NgClass

NgClass

[ngClass]

NgClass

NgClass

NgClass

Software Used

Create CSS Classes

.one { color: green; } .two { font-size: 20px; } .three { color: red; } .four { font-size: 15px; }

NgClass with String

NgClass

NgClass

<p [ngClass]="'one'"> Using NgClass with String. </p>

<p [ngClass]="'one two'"> Using NgClass with String. </p>

ngClass

ngFor

<div *ngFor="let user of users" [ngClass]="'one two'"> {{user}} </div>

NgClass with Array

NgClass

<p [ngClass]="['one', 'two']"> Using NgClass with Array. </p>

ngClass

ngFor

<div *ngFor="let user of users" [ngClass]="['one', 'two']"> {{user}} </div>

NgClass with Object

NgClass

<p [ngClass]="{'one': true, 'three': false }"> Using NgClass with Object. </p>

.one

.three

ngClass

ngFor

index

.one

.three

<div *ngFor="let user of users; let i = index"> <div [ngClass]="{'one': i%2==0, 'three':i%2==1}"> {{user}} </div> </div>

even

<div *ngFor="let user of users; let flag = even;"> <div [ngClass]="{'one':flag, 'two':flag, 'three':!flag, 'four':!flag}"> {{user}} </div> </div>

flag

.one

.two

.three

.four

NgClass with Component Method

NgClass

getCSSClasses(flag:string) { let cssClasses; if(flag == 'nightMode') { cssClasses = { 'one': true, 'two': true } } else { cssClasses = { 'two': true, 'four': false } } return cssClasses; }

NgClass

NgClass

<div [ngClass]="getCSSClasses('nightMode')"> Using NgClass with Component Method. </div>

getCSSClasses()

NgClass

Complete Example using TypeScript

.one { color: green; } .two { font-size: 20px; } .three { color: red; } .four { font-size: 15px; }

<p [ngClass]="'one two'"> Using NgClass with String. </p> <p [ngClass]="['three', 'four']"> Using NgClass with Array. </p> <p [ngClass]="{'one': true, 'three': false }"> Using NgClass with Object. </p> <div *ngFor="let user of users; let flag = even;"> <div [ngClass]="{'one':flag, 'two':flag, 'three':!flag, 'four':!flag}"> {{user}} </div> </div> <br/> <div [ngClass]="getCSSClasses('nightMode')"> Using NgClass with Component Method. </div>

import {Component} from '@angular/core'; @Component({ selector: 'user-app', templateUrl: 'app/user.component.html', styleUrls: ['app/user.component.css'] }) export class UserComponent { users = [ 'Mahesh', 'Krishna', 'Narendra', 'Jitendra' ]; getCSSClasses(flag:string) { let cssClasses; if(flag == 'nightMode') { cssClasses = { 'one': true, 'two': true } } else { cssClasses = { 'two': true, 'four': false } } return cssClasses; } }

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { UserComponent } from './user.component'; @NgModule({ imports: [BrowserModule], declarations: [UserComponent], bootstrap: [UserComponent] }) export class AppModule { }

import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {AppModule} from './module'; const platform = platformBrowserDynamic(); platform.bootstrapModule(AppModule);

<html> <head> <title>Angular 2 Demo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/reflect-metadata/Reflect.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <!-- Configure SystemJS --> <script src="systemjs.config.js"></script> <script> System.import('myApp').catch(function(err){ console.error(err); }); </script> </head> <body> <user-app>Please Wait...</user-app> </body> </html>

Run Application

References

Download Source Code

On this page we will provide angular 2 NgClass example. It is used to add and remove CSS classes on an HTML element. We can bind several CSS classes tosimultaneously that can be added or removed. There are different ways to bind CSS classes tothat are using string, array and object. CSS classes are assigned toas property binding using bracket i.eas attribute of any HTML element . We can assign one or more than one CSS classes to HTML element using. When we usewith object then adding and removing CSS classes are performed on the basis of retuned Boolean value of an expression. If the value of expression isthen respective CSS class will be added otherwise that CSS class will be removed from HTML element at run time. Now we will discuss hereexample in detail step by step using TypeScript.Find the software used in our demo.1. Angular 2.3.02. TypeScript 2.0.103. Node.js 4.6.04. NPM 3.10.85. Firefox 50.1.0For the demo we are creating four CSS classes as follows.We have two CSS classes named asand. Now to bind CSS class to, just create a string and inside it we need to refer our CSS class names enclosed by single quote ('). Find the code below. Here we are binding a single CSS class toIn case we want to add more than one CSS classes then add it separated by space.We can also usewithusing string as follows. The given CSS classes will be applied to HTML element in each iteration.Here we will discuss how to usewith array of CSS classes. Suppose we have two CSS classes named asand. We need to add our CSS classes within bracketseparated by comma (,) and enclosed by single quotes (').with array can also be used withas follows.Here we will discusswith object using braces. It will be inandpair format separated by colon: CSS class name.: An expression that returns Boolean value.Herewill be CSS class name andwill be an expression that will return Boolean value. CSS will be added at run time in HTML element only when if expression will return. If expression returnsthen the respective CSS class will not be added. Suppose we have four CSS classes named asand. Now find the below code snippet.In the above code snippet we are using two CSS classes. The expression value of CSS classis. So this CSS class will be added at runtime. Now check next CSS class used in above code snippet that isand its expression value is. So this CSS class will be removed at run time from HTML element.with object can also be used with. Find the code snippet below. Here we are usingvariable and dividing it by 2 in every iteration. When the result is 0, we are using CSS class asand if result is 1 then we are using CSS class asNow find the below code snippet. Here we are usingvariable. This variable returnsif iteration number is even otherwiseIn the above code snippet, while iteration ifvalue isthen CSS classesandwill be added to the HTML element otherwise CSS classesandwill be added to HTML element at run time.Here we will use a component method with. We will create a component method that will return a set of CSS classes. We can dynamically add or remove CSS classes from our set within the method. Find the component method used in our example.We will observe that we can create a set of classes that will returned by method. In this way in one call of method we can assign more than one CSS classes to. We can easily add or remove CSS classes in our set dynamically within component method. We will call our component method withas below.In the above code we are callingmethod that will return a set of CSS classes toon the basis of specified argument.Find the steps to run the example.1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.2. Download the source code using download link given below in the example.3. Go to the root folder of the project using command prompt and runcommand.4. Now runcommand.5. Now run index.html file. Find the print screen of the output.