Applying Conditional Cell Styles in Angular Data Grid
Environment
Product | Progress® Kendo UI® for Angular Grid |
Description
I want to style Grid cells conditionally to reflect real-world scenarios, such as highlighting the content in certain cells based on their values. For example, cells with values greater than a certain number could appear in red to indicate a warning, while cells with lower values could appear in blue to indicate normal status.
This Knowledge Base article also answers the following questions:
- How to color cells in Kendo UI for Angular Grid based on their values?
- How to apply conditional formatting to Grid cells in Angular?
- How to use templates for dynamic styling in Kendo UI for Angular Grid?
Solution
To apply conditional styling to Grid cells based on their values or other business logic, you can use the CellTemplateDirective
of the component along with Angular's class or style binding syntax. This allows you to dynamically set the cell text color through a function that determines the appropriate style for each value.
-
Implement a custom cell template for the desired Grid columns. Inside the template, wrap the cell value in a desired HTML element and bind the
color
style property dynamically using a custom function.html<kendo-grid [data]="gridData"> <kendo-grid-column field="UnitPrice" title="Unit Price"> <ng-template kendoGridCellTemplate let-dataItem> <span [style.color]="cellColor(dataItem.UnitPrice)"> {{ dataItem.UnitPrice }} </span> </ng-template> </kendo-grid-column> </kendo-grid>
-
Create a custom function in your component to determine the cell text color based on the value.
typescriptpublic cellColor(value: number): string { const color = value > 10 ? "#FF0000" : "#89CFF0"; // Return red for values greater than 10, blue otherwise. return color; }
The following example demonstrates full implementation of the suggested approach. The text in the Grid cells appears in red when the value is greater than 10, and in blue when the value is 10 or less.