Share with   

How to use ngStyle and ngClass in Angular

We are seen how we can use this ngClass and ngStyle directive in angular 4+ framework. Why we need to use ngStyle and ngClass in angular framework.


NgStyle

In angular framework when we want to use css style but in specific condition like if the list item having collection of countries and want to change colors of text of country name that time we use NgStyle attribute to change the color of text by applying condition.

 

Example

<div [ngStyle]="{'background-color':person.country === 'UK' ? 'green' : 'red' }"></<div>

In this example when the country is having UK then background color of the div is green. If its not UK country then the by default background color takes as red color.

Similarly following is the example of list of country data. By using ngStyle we assign colors by different country.

@Component({
  selector: 'ngstyle-example',
  template: `<h4>NgStyle</h4>
<ul *ngFor="let person of people">
  <li [ngStyle]="{'color':getColor(person.country)}"> {{ person.name }} ({{ person.country }}) (1)
  </li>
</ul>
 `
})
class NgStyleExampleComponent {

  getColor(country) { (2)
    switch (country) {
      case 'UK':
        return 'green';
      case 'USA':
        return 'blue';
      case 'HK':
        return 'red';
    }
  }

  people: any[] = [
    {
      "name": "Douglas  Pace",
      "country": 'UK'
    },
    {
      "name": "Mcleod  Mueller",
      "country": 'USA'
    },
    {
      "name": "Day  Meyers",
      "country": 'HK'
    },
    {
      "name": "Aguirre  Ellis",
      "country": 'UK'
    },
    {
      "name": "Cook  Tyson",
      "country": 'USA'
    }
  ];
}

Output of the above program is

 

NgClass

In angular framework we can use bootstrap for css class. By using this class we directly use css by using bootstrap classes.

The NgClass directive allows you to set the Bootstrap CSS class dynamically for a DOM element.

 

Example

[ngClass]="{'text-success':person.country === 'UK'}"

In this example when the country is having UK then the text-success class is used.

Let's implement the colored names demo app using ngClass.

<h4>NgClass</h4>
<ul *ngFor="let person of people">
  <li [ngClass]="{
    'text-success':person.country === 'UK',
    'text-primary':person.country === 'USA',
    'text-danger':person.country === 'HK'
  }">{{ person.name }} ({{ person.country }})
  </li>
</ul>
Author Image
Guest User

0 Comments