• Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
test
Code4Developers

Code4Developers

Code4Developers
  • Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
  • Angular

Angular 5 Class Binding & ngClass Directive

  • Nisarg Dave
  • May 2, 2018
  • 3 minute read
Angular
Total
0
Shares
0
0
0

In this article we will see how can we bind CSS class to HTML element (class binding) in Angular 5. We will also discuss about ngClass directive to add or remove multiple classes from HTML element with example.

Examples

I have already created first-app component in my Angular 5 application.

  • In first-component.component.css file include the following three CSS classes.
.class-success{
 color:green;
}

.class-fail{
 color:red;
}

.class-special{
 font-style: italic;
}
  • In first-app.component.ts, include an <h2> element as shown below. Notice we have set the class attribute of the <h2> element to ‘class-success’.
import { Component, OnInit } from '@angular/core';

@Component({
 selector: 'app-first-component',
 template: `<h2 class='class-success'>Code 4 Developers</h2> `,
 styleUrls: ['./first-component.component.css']
})

export class FirstComponentComponent implements OnInit {
 constructor() { }
 ngOnInit() {
 }
}

At this point, run the application and notice that the class-success is added to the <h2> element as expected.

Modify the code in first-component.component.ts as shown below.

  1. We have added a property ‘classesToApply’in FirstComponent class.
  2. We have also specified class binding for the <h2> element. The word ‘class’ is in a pair of square brackets and it is binded to the property ‘classesToApply’
  3. This will replace the existing css classes of the <h2> with classes specified in the class binding.
import { Component, OnInit } from '@angular/core';

@Component({
 selector: 'app-first-component',
 template: `<h2 class='class-success' [class]='classesToApply'>Code 4 Developers</h2> `,
 styleUrls: ['./first-component.component.css']
})

export class FirstComponent implements OnInit {
 public classesToApply='class-fail class-special'
 constructor() { }
 ngOnInit() {
 }
}

Run the application and notice class-success is removed and class-fail, class-special classes are added.

Add or Remove single class

  • To add or remove a single class, include the prefix ‘class’ in a pair of square brackets, followed by a DOT and then the name of the class that you want to add or remove.
  • The following example adds class-special to the <h2> element. Notice it does not remove the existing class-success already added using the class attribute.
  • If you change applySpecialClass property to false or remove the property from the FirstComponent class, css class is not added to the <h2> element.

Example :

import { Component, OnInit } from '@angular/core';
@Component({
 selector: 'app-first-component',
 template: `<h2 class='class-success' [class.class-special]='applySpecialClass'>Code 4 Developers</h2> `,
 styleUrls: ['./first-component.component.css']
})

export class FirstComponent implements OnInit {
 public applySpecialClass =true;
 constructor() { }
 ngOnInit() {
 }
}

You can also remove an existing class that is already applied.

Consider the following example. Notice we have 3 classes (class-success & class-special) added to the <h2> element using the class attribute. The class binding removes the class-special.

Example:

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

@Component({
 selector: 'app-first-component',
 template: `<h2 class='class-success class-special'[class.class-special]='applySpecialClass'>Code 4 Developers</h2> `,
 styleUrls: ['./first-component.component.css']
})

export class FirstComponent implements OnInit {
 public applySpecialClass =false;
 constructor() { }
 ngOnInit() {
 }
}

To add or remove multiple classes use ngClass directive as shown in the example below.

  1. Added three public property with default values in FirstComponent:
public isSuccess=false;
public isFail=true;
public isSpecial=true;
  1. Add object styleClasses having with 3 key/value pairs. The key is a CSS class name. The value can be true or false. True to add the class and false to remove the class.
public styleClasses ={
"class-success": this.isSuccess,
"class-fail":this.isFail,
"class-special":this.isSpecial
}
  1. Since two keys (class-fail & class-special) are set to true, both classes will be added to the <h2> element. Here class-success will not apply as corresponding property value isSuccess is false.
  2. Use ngClass directive with square bracket in HTML code and assign object name.
<h2 [ngClass]="styleClasses">Code 4 Developers</h2>

Example for ngClass directive:

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

@Component({
 selector: 'app-first-component',
 template: `<h2 [ngClass]="styleClasses">Code 4 Developers</h2> `,
 styleUrls: ['./first-component.component.css']
})

export class FirstComponent implements OnInit {
 public isSuccess=false;
 public isFail=true;
 public isSpecial=true;

 public styleClasses ={
  "class-success": this.isSuccess,
  "class-fail":this.isFail,
  "class-special":this.isSpecial
 }

 constructor() { }

 ngOnInit() {
 }

}

Run the application and notice class-success is not applied as the component property isSuccess is set to false but class-fail and class-special is applied because isFail is set to true and isSpecial is set to true.

Nisarg Dave
Nisarg Dave

He works as a software developer. He has hands-on experience on .net and other Microsoft technologies. He also works on AngularJS, KnockOutJS.

Views: 9,096

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Pinterest (Opens in new window) Pinterest
  • Click to email a link to a friend (Opens in new window) Email
  • Click to print (Opens in new window) Print

Like this:

Like Loading...

Related Posts

Total
0
Shares
Share 0
Tweet 0
Pin it 0

Leave a ReplyCancel reply

Subscribe to Website via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Recent Posts
  • Getting Started with AWS Step Functions: Orchestration Made Simple

    Getting Started with AWS Step Functions: Orchestration Made Simple

    1 week ago
  • React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    1 year ago
  • Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    2 years ago
  • Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    2 years ago
  • Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    2 years ago
  • Angular Custom Elements: Creating Reusable Components with Angular

    Angular Custom Elements: Creating Reusable Components with Angular

    2 years ago
  • Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    5 years ago
  • How to Build an Inclusive Esports Community

    How to Build an Inclusive Esports Community

    5 years ago
  • Best Digital Icebreakers

    Best Digital Icebreakers

    5 years ago
  • Email alerts when a docker container stopped in AWS ECS CLUSTER

    Email alerts when a docker container stopped in AWS ECS CLUSTER

    5 years ago
Subscribe to Website via Email

Enter your email address to subscribe to this website and receive notifications of new posts by email.

Featured Posts
  • javascript 1
    Spread syntax (three dots) in JavaScript
    • March 21, 2018
  • Angular 2
    Angular 6 CRUD – Part 1: Project Setup, Routing, Service
    • May 9, 2018
  • javascript 3
    Local Storage and Session Storage
    • May 22, 2017
  • Angular 4
    Angular 4 Project Structure
    • June 18, 2017
  • AWS 5
    Email alerts when a docker container stopped in AWS ECS CLUSTER
    • July 24, 2020
Code4Developers
Learning is never ending process

Input your search keywords and press Enter.

 

Loading Comments...
 

    %d