Welcome Guest! (App Version 3.1)

websitnero logo name

[ngStyle]

Usage of ngStyle

ngStyle is used to add styles to the dynamic data coming via services based on some logic in typeScript file. Otherwise simple css might not be applied as there is no specific way to add it -- for data which is still not fetched or which may have some value based on which present css should be applied.

ngStyles is used to add styles on the fly or dynamically for data coming from server in asynchronous Rest API Calls

Practical Example of [ngStyle]

Please follow the mentioned steps:

  1. Create a component 'home' using which we will demonstrate use of ngStyle
  2. We will create an array of objects (5 people) and add various CSS styles based on the object values. For example: background is red if a person is citizen of USA otherwise blue, similarly the content will be underline if 'gender' is female and font-weight is bold if person has age greater or equal to 18.

home.component.html

<ul>
  <li *ngFor="let x of students" [ngStyle]="{
    'font-weight': x.age > 18? 'bold': 'normal',
    'background': x.country == 'USA'? 'red': 'blue',
    'text-decoration': x.gender == 'female'? 'underline': 'none'
  }"> {{x.name}}, {{x.age}}, {{x.country}}</li>
</ul>

home.component.ts

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  students = [
    {name: 'Peter', age: 29, country: 'USA', gender: 'male'},
    {name: 'Lily', age: 17, country: 'UK', gender: 'female'},
    {name: 'Albert', age: 45, country: 'China', gender: 'male'},
    {name: 'Rosy', age: 25, country: 'USA', gender: 'female'},
    {name: 'Siliva', age: 15, country: 'Canada', gender: 'female'}
  ];

  constructor() { }

  ngOnInit() {
  }

}
  1. You'll get the following result.

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.