Generating Styles Dynamically
CSS is inherently static, but sometimes you need to generate styles dynamically based on some custom logic. One way to do this is to use the Style API
in Flow to set inline CSS properties on the root element directly, supplying either static or dynamically generated values:
Button btn = new Button("Click me");
btn.getStyle().set("color", "white");
btn.getStyle().set("background-color", getRandomColor());
A drawback with this approach is that it’s not possible to apply styles to parts of components, or based on their states.
Another option is to use style properties – either the built-in Lumo properties or custom ones – that are statically applied with normal CSS, but whose values are set through application logic:
vaadin-button {
color: var(--my-button-text-color);
background-color: var(--my-button-bg-color);
}
UI.getCurrent().getElement().getStyle().set("--my-button-text-color", "white");
UI.getCurrent().getElement().getStyle().set("--my-button-bg-color", getRandomColor());
The benefit of this approach is that you can target component parts and multiple components with the same style property. This can be used for example to load domain-specific styles in a white-labeled SaaS application, or to allow the user to customize UI styles, store them into a database, and load them when the user logs in.
Note
|
Style API Cannot Return Styles Applied through Stylesheets
The Style API in Flow, used through the getStyle() method, only works with inline styles – styles applied to the HTML element directly, as opposed to via stylesheets. This means that style getters, such as getStyle().get(“color”), only return values that have been applied using the Style API. It cannot return styles applied through stylesheets.
|
97e4babd-1484-4e93-bf17-3fda6d4de8d1