herby3
herby3

Reputation: 25

Vaadin Flow: How to add class name to Template

I have a Vaadin Component in a template file:

import {LitElement, html} from 'lit-element';
import '@vaadin/vaadin-text-field/vaadin-text-field.js';
import '@vaadin/vaadin-button/vaadin-button.js';

class HelloWorld extends LitElement {

    render() {
        return html`
            <div>
                <vaadin-text-field id="firstInput"></vaadin-text-field>
                <vaadin-button id="helloButton">Click me!</vaadin-button>
            </div>`;
    }
}

customElements.define('hello-world', HelloWorld);

and the server side java class file:

@Tag("hello-world")
@JsModule("./src/hello-world.ts")
public class HelloWorld extends LitTemplate {

    /**
     * Creates the hello world template.
     */
    public HelloWorld() {
        addClassName("my-style"); // Method not available!!
    }
}

In the java class I want do add a class name to the whole Template Component to style it dynamically. But the method "addClassName()" is not available in LitTemplate. Is it possible to add a class name to a LitTemplate? In the Browser Inspector I can add 'class="my-style"' to the hello-world component manually and it works.

Upvotes: 1

Views: 737

Answers (2)

Implementing HasStyle should work:

@Tag("hello-world")
@JsModule("./src/hello-world.ts")
public class HelloWorld extends LitTemplate implements HasStyle {
    public HelloWorld() {
        addClassName("my-style");
    }
}

Upvotes: 2

Hawk
Hawk

Reputation: 2142

use the HasStyle mixin to access that method:

public class HelloWorld extends LitTemplate implements HasStyle { ... }

You can see the implementation to see what's underneath https://github.com/vaadin/flow/blob/master/flow-server/src/main/java/com/vaadin/flow/component/HasStyle.java

Upvotes: 3

Related Questions