AppDividend
Latest Code Tutorials

Angular NgStyle Example | Angular 7 NgStyle Tutorial

0

Angular NgStyle directive lets you set a given DOM element’s style properties. The key is a style name, and the value is an expression to be evaluated.  The resulting non-null value, expressed in the given unit, is assigned to the given style property. It sets one or more style properties, specified as colon-separated key-value pairs.

Angular 7 ngstyle is today’s topic. An attribute directive that updates styles for the containing HTML element.  If the result of the evaluation is null, the corresponding style is removed.

Angular NgStyle Example

Content Overview

In this angular example, we are going to take a look at how we can dynamically assign CSS styles to elements using angular. 

We will take a look at different methods to dynamically assign a CSS style to an element using the style property.

If you do not have the latest Angular CLI, then you need to update your CLI. For more guidance, see this tutorial. Now, create a new project using the following command.

ng new angulardata

Now, go inside the folder and open the folder in Visual Studio Code.

Next, install the Bootstrap 4 CSS Framework using the following command. You can skip the step of installing bootstrap because we do not need too much of styling here.

npm install bootstrap --save

Now, add the bootstrap CSS file inside the angular.json file.

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

Step 1: Create a Model file.

Inside the src >> app folder, create one file called Character.ts file and add the following code inside it.

// Character.ts

export default class Character {
    actor_name: String;
    character_name: String;
    gender: String;
    status: String;
}

We will display the Game of Thrones characters and their properties like actor_name,character_namegenderstatus, etc.

The next step is to create an array of data inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import Character from './Character';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   characters: Character[] = [
    {
       actor_name: 'Peter Dinklage',
       character_name: 'Tyrion Lannister',
       gender: 'Male',
       status: 'Alive'
    },
    {
       actor_name: 'Sean Bean',
       character_name: 'Ned Stark',
       gender: 'Male',
       status: 'Dead'
    },
    {
       actor_name: 'Emilia Clark',
       character_name: 'Khaleesi',
       gender: 'Female',
       status: 'Alive'
    },
    {
       actor_name: 'Catelyn Stark',
       character_name: 'Michelle Fairley',
       gender: 'Female',
       status: 'Dead'
    }
  ];
}

Step 2: Create HTML view to display data in Angular

Now, the last step is to write the HTML code to display the data.

We will first display the data in Table Format.

Write the following code inside the app.component.html file.

<div class="container">
  <h4>NgStyle</h4>
  <div *ngFor="let celeb of characters">
     <p [ngStyle]="{'background-color':celeb.status === 'Dead' ? 'red' : 'green' }">
	{{ celeb.actor_name }} ({{ celeb.character_name }}) is {{celeb.gender}} character and {{celeb.status}}
     </p>
   </div>
</div>

In the above code, we have looped through the character’s data and display the data one by one.

Here, we have used the ngStyle directive to assign the style to the P element.

We have assigned conditional styling. So, if the character is dead, then it will show background color red otherwise green. So, we have applied the conditional styling using the ngStyle directive in Angular.

Save the file and see the output in the browser.

 

Angular 7 NgStyle Tutorial With Example | Angular NgStyle

Angular ngStyle becomes much more useful when the value is dynamic. The values in the object literal that we assign to ngStyle can be javascript expressions, which are evaluated, and the result of that expression is used as the value of the CSS property.

We can assign the following type of styling to the HTML elements using the ngStyle directive.

Set the font of the containing element to the result of an expression.

<some-element [ngStyle]="{'font-style': styleExp}">...</some-element>

Set the width of the containing element to a pixel value returned by an expression.

<some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>

Set a collection of style values using an expression that returns key-value pairs.

<some-element [ngStyle]="objExp">...</some-element>

#Add multiple CSS styles in Angular

When assigning many different styles to an item, the syntax becomes quite confusing and cluttered. This is why there is a different way of assigning styles in Angular using the ngStyle directive.

Other than the style property, ngStyle takes an object containing the style-names and their values.

See the following code example.

<div [ngStyle]="{'color': 'purple', margin: '11px', padding: '11px'}">
Millie Bobby Brown
</div>
#Binding to properties in Angular

Binding to properties, we don’t need single quotes for the value.

See the code snippet.

<div [ngStyle]="{'color': color}">
Millie Bobby Brown
</div>

#Evaluating expressions in Angular

This is how evaluating expressions with ngStyle works.

<div [ngStyle]="{'color': data ? colorP : colorQ}">
Millie Bobby Brown
</div>

#Conclusion

In this tutorial, we discovered how we could use the ngStyle directive to assign styles dynamically using Angular.

Finally, Angular NgStyle Example | Angular 7 NgStyle Tutorial.

Recommended Posts

Angular NgClass Example

Angular 7 CRUD Example

Angular 7 Pipes Example

Angular 7 Drag and Drop Example

Angular Architecture Overview

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.