Creating a Component with Multiple Elements

In this section we demonstrate how to create a component using the Element API and multiple DOM elements. We create a TextField component that supports a label.

Example: DOM structure of the component.

HTML

  1. <div>
  2. <label></label>
  3. <input>
  4. </div>

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

Java

  1. @Tag("div")
  2. public class TextField extends Component {
  3. Element labelElement = new Element("label");
  4. Element inputElement = new Element("input");
  5. public TextField() {
  6. inputElement
  7. .synchronizeProperty("value", "change");
  8. getElement()
  9. .appendChild(labelElement, inputElement);
  10. }
  11. }
  • The DOM structure is set up by marking the root element as a <div> in the @Tag annotation.

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

  • Value synchronization 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.

Java

  1. public String getLabel() {
  2. return labelElement.getText();
  3. }
  4. public String getValue() {
  5. return inputElement.getProperty("value");
  6. }
  7. public void setLabel(String label) {
  8. labelElement.setText(label);
  9. }
  10. public void setValue(String value) {
  11. inputElement.setProperty("value", value);
  12. }