[Angular] Dynamically Set Background Color For Table Columns

Ying Tung Wu
2 min readJan 20, 2021

--

While creating a dynamic data table, sometimes we may want to set the background color of each column by it’s content. The first idea came to me is to create a variable like colColor, then modify it while generating my data table. It works, but it’s not perfect.

Original stupid way to use one variable to set color for many columns<td *ngFor="let col of columns; let i = index" style="height: 50px">  
...
<div>
[style.background-color]="colColor"
<div>
...
</td>In
Result - incorrect color settings

After googling, I realized that this error was caused by using wrong way of setting color in my data table. At the beginning, I was distracted by the large amount of data. Didn’t notice that some of the columns were with wrong color. The reason for this issue is that UI update and colColor change are not consistent.

To deal with this situation, first we need to know how Angular handles UI for us. We should just give each column it’s own variable for setting background color. It sounds stupid for using this concept on large amount of data. But with the feature Angular provides, we can easily achieve our purpose and don’t really need to create that much variables manually.

While generating each column, we call function — getBackgroundColor() to dynamically get color string and set to the target column. And leave the rest background work to Angular.

Result — Correct color settings.

--

--