Angular class names based on item values

Stack Overflow Asked by mafortis on December 14, 2020

I want to know how can I add dynamic class name to my <div> based on item values in angular?


item status is open add class bg-success Or item status is pending add class bg-warning



const badgeColors = {
  'Open': 'bg-primary',
  'pending': 'bg-warning',
  'Finished': 'bg-success',
  'Expired': 'bg-danger'


<div class="col-md-3" *ngFor="let item of listOfData" :key="">
  <div class="card">
    <div class="otherClasses bg-warning"></div> <-- I need to change this static `bg-warning` to dynamic `badgeColors`

2 Answers

you can simply call ngClass on your div like


and in your ts

const badgeColors = {
  'Open': 'bg-primary',
  'pending': 'bg-warning',
  'Finished': 'bg-success',
  'Expired': 'bg-danger'

return this.badgeColors[item];

Correct answer by Hrishikesh Kale on December 14, 2020

You can use ngClass directive. For example:

<div [ngClass]="{'bg-success': (status === open), 'bg-warning': (status === pending)}"> </div>

Answered by Utkarsh Awasthi on December 14, 2020

Add your own answers!

Related Questions

Center a grouped bar chart in R (ggplot2)

2  Asked on December 20, 2021


Node js – public subfolder

1  Asked on December 20, 2021 by andres-darwin


Syntax error on getting multiple range VBA

0  Asked on December 20, 2021 by michael-norman


what can make my form not to see my input value

2  Asked on December 18, 2021 by michael-august


Regex Match/Wildcard

1  Asked on December 18, 2021 by ovenbakedpython


javascript async and await event listener: Pokemon

1  Asked on December 18, 2021 by jason-todd


Why do I want to use CRTP over simple template for static polymorphism?

2  Asked on December 18, 2021 by diveintoml


Check if string in path and do something

2  Asked on December 18, 2021


sql, delete duplicate records using an ID

2  Asked on December 18, 2021 by user12929912


Ask a Question

Get help from others!

© 2022 All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP