As the debate is going on about Angular 2 vs ReactJS I have chosen to master the former for now due to my experience and very good impression that I have with AngularJS 1.x. I would be writing a series of articles on Angular 2 going forward.
In this post I’m going to discuss about the ngClass directive.
ngClass:
This directive is used to dynamically assign a class to a HTML element in which this directive is being used. For example look at the below example:
<div [ngClass]="{'colorDiv':true, 'nonColorDiv':false}">ngClass</div>
The above div element will have the class “colorDiv” assigned rather than “nonColorDiv” as per the Boolean values assigned to them.
Now if you want the Boolean values to be dynamic then we need to create a Boolean variable in the component and then use that variable in the ngClass directive.
For example let us have a look at the below div element:
<div [ngClass]="{'colorDiv': isColorDiv, 'nonColorDiv': !isColorDiv }">ngClass</div>
The component code:
import {Component, NgModule} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' @Component({ selector: 'my-app', templateUrl: 'appTemplate.html', styleUrls: ['style.css'] }) export class App { isColorDiv:boolean; constructor() { this.isColorDiv= true; } } @NgModule({ imports: [ BrowserModule ], declarations: [ App ], bootstrap: [ App ] }) export class AppModule {}
As you see the isColorDiv variable has been declared as a Boolean variable based on which the class of the div changes.