ngStyle in angular

In this article, you will learn what is ngStyle and when and how to use it with examples.

What is ngStyle?

The ngStyle is directive in angular and you can set styles of HTML elements using it.

When to use ngStyle?

It is mostly used to set styles based on dynamic values. But you can also use it for setting static styles.

Otherwise, you can set static styles like the following:

<h1 [style.color]="'red'">Text with red background.</h1>

How to use ngStyle?

1. Using object literals

You can set styles to elements by assigning the object of style property with its value to [ngStyle].

Example:

<h1 [ngStyle]="{'background-color': 'black', 'color': 'white'}">Text with black background and white text color.</h1>

Output:

2. Using ternary operator

You can also use JavaScript expression inside an object and assign it to [ngStyle]. JavaScript expression gets evaluated and its result styles get applied to the element.

Set following property in component.

username = 'John';

Put following code in component’s template i.e HTML file

<h1 [ngStyle]="{'color': username === 'John' ? 'green' : 'blue'}">User is {{username}}.</h1>

Output:

As username is set as ‘John’, the text color will be set to green.

ngStyle-by-using-ternary-operator-or-function-1

3. Using function

You can also call a function from component to set styles for element.

Example:

Step 1: Returning styles from function

In the following code, color is returned by setColor() function based on username.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  username = 'John';

  setColor() {
    return this.username === 'John' ? 'green' : 'blue';
  }
}

Step 2: Setting styles by calling function

<h1 [ngStyle]="{'color': setColor()}">User is {{username}}.</h1>

Output:

ngStyle-by-using-ternary-operator-or-function-1

Conclusion:

From this article, you learned what is ngStyle, when to use it and how to use it. If you have problems while implementing code, you can ask me through the comment section.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments