Home  >  Angular

Angular 2 CSS Class Binding Example

By Arvind Rai, November 27, 2016
On this page we will provide angular 2 CSS class binding example. We can add and remove CSS class names from the HTML element class attribute using CSS class binding. CSS class binding is same as property binding. But we need to add a prefix class. with CSS class name in class binding. The CSS class added by class binding will override the existing CSS class properties if any property will be common. CSS class binding removes CSS class when expression returns false and adds it when expression returns true.
To add or remove more than one CSS class dynamically we should use NgClass directive. Find the link.

Angular 2 NgClass Example

Now here on this page we will discuss complete example of CSS class binding step by step using TypeScript.

Software Used

Find the software used in our demo.
1. Angular 2.3.0
2. TypeScript 2.0.10
3. Node.js 4.6.0
4. NPM 3.10.8
5. Firefox 50.1.0

Create CSS Classes

Find the CSS classes which we will use in our example.
.required{
    color: green;
    font-size: 30px;
}
.optional {
    color: red;
    background-color: cyan;
    font-family: cursive;
} 

CSS Class Binding

Class binding is same as property binding with the difference that we need to prefix class name with class. . The syntax of using class binding is as follows.
<div [class.required]="isReq">Hello Wordl!</div>  
Here required is a CSS class name. We need to prefix it with class. . Here we are using bracket [] for class binding. We can also use bind- keyword with the target. Class binding also works with interpolation. Find the code snippet.
<div bind-class.required ="isReq">Hello Wordl!</div>
<div class.required ="{{isReq}}">Hello Wordl!</div>  
In the above code snippet first line is using bind- keyword and second line is using interpolation. We have defined isReq a component property which is Boolean. In the above class binding we control our class dynamically. If the value of isReq is true only when the CSS class required will be applied in the <div> element.
In normal HTML coding CSS class is used as follows.
<div class="required">Hello Wordl!</div>  
Now to understand more about class binding, I am creating a method in component as follows.
isOptional(data) {
   if (data == 'yes') {
       return true;
   } else {
       return false;
   }
}  
In the above method when we pass "yes", method will return true otherwise false. We will discuss different scenarios now. Here we are using HTML element class attribute as well as angular class binding. We are adding two CSS classes that is required and optional .
1. The component method isOptional('yes') returns true, so <div> tag will have both the CSS classes. The CSS properties of optional class will override the CSS properties of required class if there is any common property.
<div class="required" [class.optional]="isOptional('yes')">Hello Wordl!</div>  


2. Here optional class will not include in <div> because isOptional('no') will return false value.
<div class="required" [class.optional]="isOptional('no')">Hello Wordl!</div>  


3. Here we consider a scenario in which we are using both CSS classes using regular HTML element class attribute. Now using angular class binding we can on/off CSS classes. If isOptional() method returns true, then both the CSS classes will work and if isOptional() method returns false, then optional CSS class will be removed.
<div class="required optional" [class.optional]="isOptional('no')">Hello Wordl!</div>  
In above code only required CSS class will work.

Complete Example using TypeScript


app.component.ts
import {Component} from '@angular/core';
@Component({
    selector: 'my-app',
    templateUrl: 'app/app.component.html',
    styleUrls: ['app/app.component.css']
})
export class AppComponent {
	isReq = true;
	isOptional(data) {
	   if (data == 'yes') {
	       return true;
	   } else {
	       return false;
	   }
	}
}  
app.component.css
.required{
    color: green;
    font-size: 30px;
}
.optional {
    color: red;
    background-color: cyan;
    font-family: cursive;
} 
app.component.html
<div class="required">Hello Wordl!</div>

<div [class.required]="isReq">Hello Wordl!</div>

<div class="required" [class.optional]="isOptional('yes')">Hello Wordl!</div>

<div class="required" [class.optional]="isOptional('no')">Hello Wordl!</div>

<div class="required optional" [class.optional]="isOptional('no')">Hello Wordl!</div> 
module.ts
import {NgModule}       from '@angular/core';
import {BrowserModule}  from '@angular/platform-browser';
import {AppComponent}   from './app.component';
@NgModule({
  imports:      [BrowserModule],
  declarations: [AppComponent],
  bootstrap:    [AppComponent]
})
export class AppModule { } 
main.ts
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);  
index.html
<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>
    <my-app>Please Wait...</my-app>
  </body>
</html> 

Run Application

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 run npm install command.
4. Now run npm start command.
5. Now run index.html file. Find the print screen of the output.
Angular 2 CSS Class Binding Example

Reference

Angular 2 Class Binding

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us