Angular 7 NgClass and NgStyle Explained

Article By Rawat Digamber on

Angular 7 NgClass

NgClass and NgStyle in Angular 7 will be explored in detail in this article. As far as class manipulations in Angular 7 are concerned, whether it is toggling, removing or adding, we have plenty of options before us. We will be able to bind a property to single classes. Alternatively, we can depend on the fantastic NgClass directive available in Angular 7.

Here in this article, we are going to take a closer look at class bindings. Moreover, we will be examining Angular 7 NgClass directive in detail. We will look into the best practice ideas and the syntaxes.

When it comes to DOM, we are required to add a specific type of “state” to it more often than not. Usually, we achieve the same with the help of classes. Angular has easy and quick options for us to play with. Let’s have a look below:

Examples Property Binding with className in Angular 7

Before we decode the NgClass, we are going to take a closer look at some sugar syntax which is known for its effectiveness and simplicity. When it comes to working with single classes, we prefer this method over NgClass. Why because this method works much faster. On top of it, this method is so much more descriptive when we look into the existing code.

Well, let’s find out how it looks like. We are going to look at NgClass examples below.

When it comes to JavaScript DOM, we are bestowed with the className property which can be used in connection with DOM elements.

const section = document.querySelector('section');

section.className = 'Hey There!';

console.log(section.className); 

// 'Hey There!'

See, it is simple and easy! However, then we need to remember the fact that in Angular we are mostly dealing with bindings and templates. We do not use DOM APIs.

It’s a common knowledge that we do not bind to attributes but properties when it comes to NgClass Angular 7. Also, that suggests that we can utilize this knowledge into:

<div [className]="'activeClass'"></div>

Angular will be looking up for the JavaScript property of className, will be binding the expression to it.

Well, let’s take the example of interpolation for reference here:

<p>{{ content }}</p>

Well, in reality, we are looking at the sugar syntax for:

@Component({
  selector: 'my-app',
  template: `
    <p [innerText]="content"></p>
  `,
})

export class AppComponent  {
  content: string = 'The lazy fox jump over the wall';
}

Well, instead of deviating from the point, let’s come back to explore classes. Maybe we need to give a conditional to the className in Angular 7:

<div [className]="condition ? 'if-true' : 'then-false'"></div>

We would like to avoid this. And we would prefer supplying a class always. Well, can we focus on just a single class?

Binding NgClass in Angular 7

What I love about Angular is that it serves a shorthand syntax to supply a class.

@Component({
  selector: 'my-app',
  template: `
    <div [class.activeClass]="condition">I am content with active class</div>
  `,
})

export class AppComponent  {
  condition = true;
}

The condition will be evaluated. When it returns true the class of activeClass will be included. Also, when it returns false, the activeClass will cease to exist. We find this method concise, clean and simple.

Now we must examine more complex classes.

@Component({
  selector: 'my-app',
  template: `
    <div [class.is-activeClass]="condition"></div>
  `,
})

export class AppComponent  {
  condition = true;
}

That’s pretty much everything we need. Here we aren’t required to provide the is-activeClass as part of a string. This is what is expected whenever you use a dash. Well, that is exactly why we need a more flexible approach like NgClass in Angular 7. We prefer using it especially when we are dealing with multiple classes.

How to Work With Multiple Classes Using NgClass in Angular 7?

At this point, we know how to remove or add single classes with the assistance of NgClass directive in Angular 7. Well, it’s time for us to explore the same with multiple classes. There are 3 ways we can apply CSS clases in Angular. Here we must keep in mind that the condition we pass will be evaluated. This suggests that we will be able to use negate expressions or ternary statements.

NgClass Expression Examples in Angular 7

PropertyDetail
stringThe CSS classes placed in the string are included.
ArrayThe CSS classes mentioned as Array elements are included.
ObjectKeys are CSS classes that get attached when the expression presented in the value examined to be a truthy value. Otherwise, they are discarded.

Angular 7 Multiple Classes Example Using NgClass String, Array and Object Expression

<div [ngClass]="'classOne classTwo'">...</div>

<div [ngClass]="['classOne', 'classTwo']">...</div>

<div [ngClass]="{'One': true, 'Two': true, 'Three': false}">...</div>

<div [ngClass]="string | array | obj">...</div>

<div [ngClass]="{'classOne classTwo classThree' : true}">...</div>
@Component({
  selector: 'my-app',
  template: `
    <div [ngClass]="{
      'activeClass': condition,
      'inactiveClass': !condition,
      'focusClass': condition && otherCondition
    }"> 
     Little boy jump over the wall
    </div>
  `,
})

export class AppComponent  {
  condition = true;
  otherCondition = true;
}

Decoding NgClass and NgStyle in Angular 7

Back in the day, Angular 1 required directives like ng-style and ng-class. Moreover, that is so special with Angular as we have these directives as inbuilt directives. To explore complex ways to change the element styles, these directives provide us with syntactic sugar. We are going to see the case of ngStyle in Angular 7 first below:

 <div [ngStyle]="{'color': 'Red', 'font-size': '45px', 'font-weight': 'bold'}">I am a class</div>

When we take a closer look at this example, we will be able to style multiple properties with very little difficulty thanks to ngStyle in Angular 7. Moreover, we have the provision to bind values to these properties. And these values can be altered by the components or user.

@Component({
  selector: 'my-app',
  template: `
    <div [ngStyle]="{'color': color, 'font-size': size}">
      Manage Dynamic Style with Angular
    </div>
    
    <input [(ngModel)]="color" placeholder="Enter color name" /><br>
    <input [(ngModel)]="size" placeholder="Enter font size" />
  `,
})

export class AppComponent  {
  
}

We are going to look at the ngClass directive next. It provides us with lot of options to update classes on HTML elements and components. We will look into ngStyle Angular examples in this article.

<div [ngClass]="['boldText', 'red']">classes of Array</div>
<div [ngClass]="'italicText orange'">classes of string</div>
<div [ngClass]="{'tinyText': true, 'blue': true}">classes of object</div>

As it happens in the case of ngClass, ngStyle allows playing with the CSS. You may toggle or add elements to the CSS with the help of ngStyle. We will be able to bind these directly to the properties of the components. Also, later we can update them as and when required dynamically.

Decoding NgStyle Directive in Angular 7

All thanks to the NgStyle directive in Angular 7, you will be able to set style properties to DOM elements.

With the help of NgStyle, we will be able to set style in a relaxed manner. Here we will be assigning object literal to it.

<div [ngStyle]="{'background-color': 'blue'}">Hello World!</div>

With the help of this code, we will be setting background color blue to div.
An important thing to keep in mind is that using dynamic values makes ngStyle even more useful. As far as the values are concerned, we can use JavaScript expressions.

We will be assigning these values to ngStyle via object literal in Angular 7. We can use the result of the JavaScript expression as the value that will be assigned to the CSS property. We have elaborated the same in the following example:

<div [ngStyle]="{'background-color':user.state === 'Ohio' ? 'blue' : 'green' }">Cincinnati Ohio</div>

As you can see in the above example, we assign a blue color to the background if the state of the person turns out to be Ohio. Else, we opt for green.

However, as you can see, we don’t need the expression to be inline. Instead, we will be making use of a function on the component.

To elaborate on this, we will be using a full example. We are going to loop through an array with names of people as we have explored in the previous examples. We intend to print out the names of these people with corresponding colors depending on the state they belong to.

Setting Up Dynamic Color Using NgStyle in Angular 7

@Component({
  selector: 'my-app',
  template: `<h4>NgStyle Example in angular 7 </h4>
  <ul *ngFor="let person of data">
    <li [ngStyle]="{'color': setUserColor(person.state)}"> {{person.name}}
    </li>
  </ul>
 `
})

export class AppComponent  {
 
  setUserColor(state) {
    switch (state) {
      case 'Chicago':
        return 'blue';
      case 'New Jersey':
        return 'red';
      case 'California':
        return 'green';
    }
  }
 
  data: any[] = [
    {
      "name": "Henry",
      "state": 'LA'
    },
    {
      "name": "Shane",
      "state": 'Chicago'
    },
    {
      "name": "AJ",
      "state": 'St Louis'
    },
    {
      "name": "Parker",
      "state": 'New Jersey'
    },
    {
      "name": "Mett",
      "state": 'California'
    }
  ];

}

We looked at the value returned by the setUserColor() function. Also, changed the color of the text value.

Depending on the state of origin for each name in the array, the setUserColor() function returns different colors.

When we run the above code we will get the following output:

Individual Styling [style.propertyName] with Angular 7 Style Property

Well, we can rely on an alternative syntax here. To individual style properties in Angular, we can rely on

// Syntax
[style.<property>]

// NgStyle Property
[style.color]="setUserColor(person.state)"
  <ul *ngFor="let person of data">
    <li [style.color]="setUserColor(person.country)">{{ person.name }} ({{ person.state }})</li>
  </ul>

Playing with Points and Pixels with Angular 7

[ngStyle]="{'font-size':20}"

But you need to know that it is not going to work. This is not a valid way to change the font in CSS. We must specify a unit, be it px or rem. Well, Angular is here to help you with the same. You can use the [property.unit] Syntax here. So, in order to set 20 font size, we would write

[ngStyle]={font-size.px’:20}

Remember

The name of the property here is font-size.px. Remember the fact that font-size is an invalid property.

What does .px suffix tell you?

It lets you know that you are going to set the font size in pixels. The same way, by choosing .rem you specify that you will be setting font size in ems. You can specify font size using % as well. The same rules are applicable in the case of alternative syntax as well.

Let’s take a look below:

[style.font-size.rem]="1"

Now we are going to bring the same changes in the demo application as well by altering the font size to 26 px below:

@Component({
  selector: 'my-app',
  template: `<h4>NgStyle Example in angular 7 </h4>
    <ul *ngFor="let person of data">
      <li [ngStyle]="{'font-size.px':26}"
          [style.color]="setUserColor(person.state)">{{ person.name }}
      </li>
    </ul>
 `
})

export class AppComponent  {
 
  setUserColor(state) {
    switch (state) {
      case 'Chicago':
        return 'blue';
      case 'New Jersey':
        return 'red';
      case 'California':
        return 'green';
    }
  }
 
  data: any[] = [
    {
      "name": "Henry",
      "state": 'LA'
    },
    {
      "name": "Shane",
      "state": 'Chicago'
    },
    {
      "name": "AJ",
      "state": 'St Louis'
    },
    {
      "name": "Parker",
      "state": 'New Jersey'
    },
    {
      "name": "Mett",
      "state": 'California'
    }
  ];

}

Feel free to contact me, If you are looking for a freelance web and mobile app developer in India, with the following skills: Angular JS, Angular 2+, Node JS, Firebase, MongoDB, Ionic Framework and WordPress.

I also offer remote contracting services to clients across the globe.

Get Started