Home > Back-end >  VaadinGrid with default component variant
VaadinGrid with default component variant

Time:12-21

I want to define all VaadinGrids in my Application with the component variant GridVariant.LUMO_ROW_STRIPES. I don't want repeat the definition on all grid instances as shown below.

grid.addThemeVariants(GridVariant.LUMO_ROW_STRIPES);

Is there any way to do this with a global configuration or something else?

I have tried so far to use the @Theme Annoation to define a theme variant. But this doesn't work.

CodePudding user response:

As already mentioned in the comment, one approach is to create a subclass of Grid, apply the variant to it, and use it instead of the Grid class in your app.

Another option is to apply the CSS with which the variant is implemented to the Grid in your own theme. It's only 4 lines of CSS: https://github.com/vaadin/web-components/blob/master/packages/grid/theme/lumo/vaadin-grid-styles.js#L312-L316

Just remove the [theme~='row-stripes'] parts from the selector, and load that css into the Grid's shadow DOM e.g. by placing it in themes/your-app-theme/components/vaadin-grid.css

CodePudding user response:

One option is to subclass Grid and add the variant in the constructor:

public class MyGrid extends Grid {
  public MyGrid() {
    addThemeVariant(GridVariant.LUMO_ROW_STRIPES);
  }
}

Another option is to copy-paste the variant CSS to your own custom theme, and remove the host selector, so that that styles are not scoped to any variant:

frontend/themes/myapp/components/vaadin-grid.css:

[part~='row']:not([odd]) [part~='body-cell'],
[part~='row']:not([odd]) [part~='details-cell'] {
  background-image: linear-gradient(var(--lumo-contrast-5pct), var(--lumo-contrast-5pct));
  background-repeat: repeat-x;
}

If you're using Vaadin 24 (prerelease at the time of writing), you can use the new recommended way of styling (avoid injecting styles into the shadow root of the component):

frontend/themes/myapp/styles.css:

vaadin-grid::part(even-row-cell),
vaadin-grid::part(even-row-cell details-cell) {
  background-image: linear-gradient(var(--lumo-contrast-5pct), var(--lumo-contrast-5pct));
  background-repeat: repeat-x;
}
  • Related