×

iFour Logo

ngStyle in Angular for Dynamic styling

Kapil Panchal - December 22, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
ngStyle in Angular for Dynamic styling

In this blog, we will be going to learn about the styling of Angular components using the ngStyle core directives. We will look at the various ways to dynamically assign a CSS style to an element using the style property.

 

Table of Content

If you don’t have the latest version of the angular cli then you need to update the angular cli latest version. After that installing angular CLI, you can use angular CLI to create a new angular project using the following command.

    ng new styleDemo
                    
 

Next, we are using bootstrap for better design and install the bootstrap using this command:

    npm install bootstrap --save 
                    
 

After installing bootstrap, add the bootstrap to the angular.json file.

    "styles": [ 
    "src/styles.scss", 
    "node_modules/bootstrap/dist/css/bootstrap.min.cs"
    ], 
                    

What is a Style attribute?

The Style attribute is used for the style of a view element. We can set the inline styles using the style attribute.

Syntax:

software-product-successful

As you can see from the above example of the style attribute, this sets the background color of the p tag to red

The declaration block can have one or more declarations.

software-product-successful

The string assigned to the style attribute contains the CSS style declaration block. In the declaration block, declaration CSS property and value.

Style declaration:
 

    selector {
    css-property: value;
    css-property: value;
    }
                    

Example of the style attribute:

software-product-successful

The inline style for the p element styles from the selector.

   

Property binding with style:

Property binding is used for the styling of one CSS property. We can style only one property

Syntax:

software-product-successful

Example of the property binding with the style:

software-product-successful

In this example, the square brackets represent a property binding and contain the property to update dynamically.

Style binding will also have the unit. Some CSS properties need a unit of measurement like font-size, padding, margin, width, height, etc

software-product-successful

Example:

In the app.component.html file, we can write the style property.

software-product-successful

In the app.component.ts file, we can set the isValid value to true.


    import { Component } from '@angular/core';
    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
    title = 'NgStyleDemo';
    isValid = true;
    }					
    

What is the NgStyle?

The NgStyle attribute is used to change the appearance and behavior of the element. NgSytle is most useful when the value is dynamic.

We can set the styles using the ngStyle directive.

software-product-successful

As you can see in the above example of the NgStyle, this sets the background color of the div to red.

We can add multiple CSS properties in a ngStyle directive.

software-product-successful

As you can see in the above example of the ngStyle, this sets the multiple CSS properties to the div element like background-color, color, font-size, etc.

Example 1

In this example, we will use ngStyle for styling and can write the inline CSS on the element.

software-product-successful

Example 2

app.components.ts

 
    import { Component } from '@angular/core';
    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
    title = 'NgStyleDemo';
      
    myCss = {
    'background-color' : 'green',
    'color' : 'white', 
    'font-size' : '40px',
    'font-weight' : 'bold',
    };
    }
                    
app.component.html

software-product-successful

In this example, we can write the CSS in the app.component.ts file and use the CSS variable in the ngstyle directive in the app.component.html file.

Example 3

Step 1: In the ngstyle.component.ts file, we can declare an array of the data.

    import { Component, OnInit } from '@angular/core';
    @Component({
      selector: 'app-ngstyle',
      templateUrl: './ngstyle.component.html',
      styleUrls: ['./ngstyle.component.scss']
    })
    export class DirectiveComponent implements OnInit {
      constructor() { }
      ngOnInit(): void {
      }
      people: any[] = [
        {
          "name": "Keval Patel",
          "country": 'India'
        },
        {
          "name": "Mcleod Mueller",
          "country": 'USA'
        },
        {
          "name": "Aniket Badrakiya",
          "country": 'UK'
        },
        {
          "name": "Neel Patel",
          "country": 'India'
        },
        {
          "name": "Cook Tyson",
          "country": 'USA'
        },
        {
          "name": "Vishal Rathod",
          "country": 'India'
        }
      ];
    }
    
    

Step 2: Create an HTML view.

software-product-successful

Example 4
    import { Component } from '@angular/core';
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      title = 'NgStyleDemo';
      people: any[] = [
        {
          "name": "Keval Patel",
          "country": 'India'
        },
        {
          "name": "Mcleod Mueller",
          "country": 'USA'
        },
        {
          "name": "Aniket Badrakiya",
          "country": 'UK'
        },
        {
          "name": "Neel Patel",
          "country": 'Canada'
        },
        {
          "name": "Cook Tyson",
          "country": 'USA'
        },
        {
          "name": "Vishal Rathod",
          "country": 'UK'
        },
        {
          "name": "Meha Patel",
          "country": 'India'
        },
        {
          "name": "Ayush Desai",
          "country": 'Australia'
        },
        {
          "name": "Riya Rathod",
          "country": 'Canada'
        }
      ];
      getColor(country) {
        switch (country) {
          case 'India':
            return 'blue';
          case 'UK':
            return 'red';
          case 'Australia':
            return 'yellow';
          case 'USA':
            return 'green';
          case 'Canada':
            return 'orange';
        }
      }
    }
    
    
    

Looking to hire dedicated Angular Developer? Your Search ends here.

 

Create a HTML view to display the data.

software-product-successful

You should see an output like below:

software-product-successful

Alternate Syntax of the above example:

software-product-successful

Conclusion

In this blog, we described that what is style attribute and how to use the same. We have explained what is NgStyle directive in Angular for Dynamic styling and discussed a few various sets of examples for the NgStyle.

ngStyle in Angular for Dynamic styling In this blog, we will be going to learn about the styling of Angular components using the ngStyle core directives. We will look at the various ways to dynamically assign a CSS style to an element using the style property.   Table of Content 1. What is a Style attribute? 2. What is the NgStyle? 3. Conclusion If you don’t have the latest version of the angular cli then you need to update the angular cli latest version. After that installing angular CLI, you can use angular CLI to create a new angular project using the following command. ng new styleDemo   Next, we are using bootstrap for better design and install the bootstrap using this command: npm install bootstrap --save   After installing bootstrap, add the bootstrap to the angular.json file. "styles": [ "src/styles.scss", "node_modules/bootstrap/dist/css/bootstrap.min.cs" ], What is a Style attribute? The Style attribute is used for the style of a view element. We can set the inline styles using the style attribute. Syntax: As you can see from the above example of the style attribute, this sets the background color of the p tag to red The declaration block can have one or more declarations. The string assigned to the style attribute contains the CSS style declaration block. In the declaration block, declaration CSS property and value. Style declaration:   selector { css-property: value; css-property: value; } Example of the style attribute: The inline style for the p element styles from the selector.   Read More: Angular Localization With Ivy   Property binding with style: Property binding is used for the styling of one CSS property. We can style only one property Syntax: Example of the property binding with the style: In this example, the square brackets represent a property binding and contain the property to update dynamically. Style binding will also have the unit. Some CSS properties need a unit of measurement like font-size, padding, margin, width, height, etc Example: In the app.component.html file, we can write the style property. In the app.component.ts file, we can set the isValid value to true. import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'NgStyleDemo'; isValid = true; } What is the NgStyle? The NgStyle attribute is used to change the appearance and behavior of the element. NgSytle is most useful when the value is dynamic. We can set the styles using the ngStyle directive. As you can see in the above example of the NgStyle, this sets the background color of the div to red. We can add multiple CSS properties in a ngStyle directive. As you can see in the above example of the ngStyle, this sets the multiple CSS properties to the div element like background-color, color, font-size, etc. Example 1 In this example, we will use ngStyle for styling and can write the inline CSS on the element. Example 2 app.components.ts   import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'NgStyleDemo'; myCss = { 'background-color' : 'green', 'color' : 'white', 'font-size' : '40px', 'font-weight' : 'bold', }; } app.component.html In this example, we can write the CSS in the app.component.ts file and use the CSS variable in the ngstyle directive in the app.component.html file. Example 3 Step 1: In the ngstyle.component.ts file, we can declare an array of the data. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ngstyle', templateUrl: './ngstyle.component.html', styleUrls: ['./ngstyle.component.scss'] }) export class DirectiveComponent implements OnInit { constructor() { } ngOnInit(): void { } people: any[] = [ { "name": "Keval Patel", "country": 'India' }, { "name": "Mcleod Mueller", "country": 'USA' }, { "name": "Aniket Badrakiya", "country": 'UK' }, { "name": "Neel Patel", "country": 'India' }, { "name": "Cook Tyson", "country": 'USA' }, { "name": "Vishal Rathod", "country": 'India' } ]; } Step 2: Create an HTML view. Example 4 import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'NgStyleDemo'; people: any[] = [ { "name": "Keval Patel", "country": 'India' }, { "name": "Mcleod Mueller", "country": 'USA' }, { "name": "Aniket Badrakiya", "country": 'UK' }, { "name": "Neel Patel", "country": 'Canada' }, { "name": "Cook Tyson", "country": 'USA' }, { "name": "Vishal Rathod", "country": 'UK' }, { "name": "Meha Patel", "country": 'India' }, { "name": "Ayush Desai", "country": 'Australia' }, { "name": "Riya Rathod", "country": 'Canada' } ]; getColor(country) { switch (country) { case 'India': return 'blue'; case 'UK': return 'red'; case 'Australia': return 'yellow'; case 'USA': return 'green'; case 'Canada': return 'orange'; } } } Looking to hire dedicated Angular Developer? Your Search ends here. See here   Create a HTML view to display the data. You should see an output like below: Alternate Syntax of the above example: Conclusion In this blog, we described that what is style attribute and how to use the same. We have explained what is NgStyle directive in Angular for Dynamic styling and discussed a few various sets of examples for the NgStyle.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Power Apps vs Power Automate: When to Use What?
Power Apps vs Power Automate: When to Use What?

I often see people asking questions like “Is Power App the same as Power Automate?”. “Are they interchangeable or have their own purpose?”. We first need to clear up this confusion...

Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula
Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula

We always hear about how important it is to be competitive and stand out in the market. But as an entrepreneur, how would you truly set your business apart? Is there any way to do...

React 18 Vs React 19: Key Differences To Know For 2024
React 18 Vs React 19: Key Differences To Know For 2024

Ever wondered how a simple technology can spark a revolution in the IT business? Just look at React.js - a leading Front-end JS library released in 2013, has made it possible. Praised for its seamless features, React.js has altered the way of bespoke app development with its latest versions released periodically. React.js is known for building interactive user interfaces and has been evolving rapidly to meet the demands of modern web development. Thus, businesses lean to hire dedicated React.js developers for their projects. React.js 19 is the latest version released and people are loving its amazing features impelling them for its adoption.