Home > Blockchain >  How to set the cell color dynamically in grid header by it's value
How to set the cell color dynamically in grid header by it's value

Time:09-30

I am trying to dynamically change the color of header cells

The columns with header in grid are generated dynamically too:

for (Employee emp : employees) {
     Grid.Column<Employee> empColumn = grid.addColumn(...).setHeader(emp.getNameWithEmpRelationship());
}

But I only know how to change the color of whole header row, not only for cell

My custom .css file:

:host(.header-change) [part~="header-cell"] {
  background-color: #ececec;
  color: black;
}

Then I added it into the grid

grid.addClassName("header-change");

And result looks like:

enter image description here

But I need to do something like this:

for (Employee emp : employees) {
     Grid.Column<Employee> empColumn = grid.addColumn(...).setHeader(emp.getNameWithEmpRelationship());
     
     if(emp.getNameWithEmpRelationship().name().equals("CONTRACT") {
        empColumn.addClassName("orange-cell");
     }

     if(emp.getNameWithEmpRelationship().name().equals("PART_TIME") {
        empColumn.addClassName("green-cell");
     }

     if(emp.getNameWithEmpRelationship().name().equals("FULL_TIME") {
        empColumn.addClassName("blue-cell");
     }

}

.css should looks like:

.orange-cell {
  background-color: orange;
  color: black;
}

.blue-cell {
  background-color: blue;
  color: black;
}

.green-cell {
  background-color: green;
  color: black;
}

And the result should looks like (I achieved the sample result by manually adjusting the value of the element through the browser):

enter image description here

How can I do this? Because my example is not working.

CodePudding user response:

I'm afraid the short answer is that you can't. While you can apply css classnames, and thus styling, to body cells, using ClassNameGenerator, that does not work for header cells.

What you can do is use a component for the header cells' contents, using Column.setHeader(Component c); Then you can of course apply styling whichever way you like to that component.

However, that component is not going to cover the entire space. While it's technically possible to make that happen with css, it's complicated, error prone, and not really supported.

There's a feature request ticket for this here: https://github.com/vaadin/web-components/issues/1434. You can vote for the feature by adding a thumbs-up reaction.

  • Related