Welcome Guest! (App Version 5.16)

websitnero logo name


Usage of ngClass

ngClass is very similar to ngStyle, the only difference being we apply CSS now via class instead of writing it as inline style earlier.

Practical Examples of [ngClass]

Please follow the mentioned steps:

  1. Create a compennt 'home' which we will use as parent
  2. Create a component 'hearts' that we will use as child
  3. Add the home component in the app.component.html file removing all boilerplate code there.
  4. Add the [ngClass] in home.component.html with conditions. In home.component.ts file make an array from which values will be fetched. The classes which will be added conditionally should be written in home.component.css file.


  <li *ngFor="let x of students" [ngClass]="[
    (x.age > 18)? 'bold': '',
    x.country == 'USA'? 'red':'blue',
    x.gender == 'female'? 'underline': ''
  ]"> {{x.name}}, {{x.age}}, {{x.country}}</li>


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

  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() {



.blue {background:blue;}
.red {background:red;}
.bold {font-weight:bold;}
.underline {text-decoration:underline;}
  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.