Docs

Documentation versions (currently viewingVaadin 24)

Creating a Component with Multiple Elements

Creating a component using multiple HTML elements.

This section demonstrates how to create a component using the Element API and multiple DOM elements, by creating a TextField component that supports a label.

Example: DOM structure of the component.

<div>
    <label></label>
    <input>
</div>

Example: TextField component with <input> and <label> elements

@Tag("div")
public class TextField extends Component {

    Element labelElement = new Element("label");
    Element inputElement = new Element("input");

    public TextField() {
        inputElement
            .addPropertyChangeListener("value", "change", e -> {});
        getElement()
            .appendChild(labelElement, inputElement);
    }

}
  • The DOM structure is created by marking the root element as a <div> in the @Tag annotation.

  • The label and input elements are appended to the root element.

  • Synchronization of the value property is set up using the input element.

See Creating a Simple Component Using the Element API for an alternative way to synchronize.

Adding an API

To make the component easier to use, you can add an API to set the input value and label text.

Example: Adding an API to get and set values for the input and label elements.

  public String getLabel() {
      return labelElement.getText();
  }

  public String getValue() {
      return inputElement.getProperty("value");
  }

  public void setLabel(String label) {
      labelElement.setText(label);
  }

  public void setValue(String value) {
    inputElement.setProperty("value", value);
  }

AF6AD086-B42A-43BF-9013-48ED5FCB2FD8