Stephane Grenier
Stephane Grenier

Reputation: 15925

Is it possible to programatically set the styles in a Vaadin 14 / Flow grid

For example I have a grid where I let the user define the colors for certain data using Vaadin 8 and I'd like to offer this in Vaadin 14 / Flow as well.

In Vaadin 8 I did (for each style/data type):

Page.getCurrent().getStyles()
    .add(".MyCustomTheme .v-grid-cell." + cssName + " { background-color:" + userSelectedColor + "; }");

then in the grid code I would do:

addColumn(myColumn).setStyleGenerator(cssName);

In Vaadin 14 / Flow I have:

addColumn(myColumn).setClassNameGenerator(cssName);

However I can't seem to figure out how to programmatically change the css values for cssName. In essence how do I do the first part where I inject my css in the Java code?

Just to add I couldn't do anything as shown here at: https://vaadin.com/docs/v14/flow/element-api/tutorial-dynamic-styling When I tried to do grid.getElement().getStyle().set(...) this would apply to the whole table rather than the rows.

Upvotes: 2

Views: 1079

Answers (1)

Tatu Lund
Tatu Lund

Reputation: 10643

One option is to use TemplateRenderer to inject styles, here is an example.

grid.addColumn(TemplateRenderer.<Bean> of(
        "<div style$=\"[[item.styles]]\">[[item.data]]</div>")
        .withProperty("styles", "color: red")
        .withProperty("data", Bean::getData));

Also note, that Grid's table and its cells are in shadow DOM. So if you are using setClassNameGenerator, you need to set the styles in style module for Grid, instead of global css. I.e. set the generator

grid.addColumn(..).setClassNameGenerator(item -> item.getData() < 0 ? "red" : null);

Add the import for css

@CssImport(value = "my-grid-styles.css", themeFor = "vaadin-grid")

And in "frontend/my-grid-styles.css" use

.red {
   color: red;
}

Note, like explained in other answer, you can also set the color to be from css property.

.red {
   color: var(--my-grid-cell-color);
}

Then, you can just define the value of that color in Grid scope using (JavaScript call is not needed)

grid.getElement().getStyle().set("--my-grid-cell-color","red");

Upvotes: 7

Related Questions