Using API Helpers to Define Component Properties

The PropertyDescriptor interface (and associated PropertyDescriptors helper class) simplifies managing attributes and properties in a component.

You can use PropertyDescriptors to define a property name and default value in a single place, and then use the descriptor from the setter and getter methods.

Example: Using the PropertyDescriptors.propertyWithDefault method to define the default property value.

@Tag("input")
public class TextField extends Component {
    private static PropertyDescriptor<String, String>
        VALUE = PropertyDescriptors
                .propertyWithDefault("value", "");

    public String getValue() {
        return get(VALUE);
    }
    public void setValue(String value) {
        set(VALUE, value);
    }
}

For your component API for a given property, for example the value of an input field, to function correctly:

  • The getter and setter should use the same property or attribute.

  • The default value should be handled correctly.

  • The getter return value should be either:

    • The type used by the setter, for example String for an input value, or

    • An optional version of the type used by the setter, that is Optional<String> if the property is not mandatory.

PropertyDescriptors automatically take the above into consideration.

PropertyDescriptor Interface

PropertyDescriptor instances are created using the helper methods available in the PropertyDescriptors class.

Different helper methods, depending on how you want your component to work, are available:

  • PropertyDescriptors.propertyWithDefault maps to an element property with a given default value.

  • PropertyDescriptors.attributeWithDefault maps to an element attribute with a given default value.

  • PropertyDescriptors.optionalAttributeWithDefault maps to an element attribute with a given default value, but returns an empty Optional when the default value is set.

Example: Using PropertyDescriptors.optionalAttributeWithDefault method for a non-mandatory placeholder in a TextField.

@Tag("input")
public class TextField extends Component {
  private static PropertyDescriptor<String,
    Optional<String>> PLACEHOLDER = PropertyDescriptors
       .optionalAttributeWithDefault("placeholder", "");

  public Optional<String> getPlaceholder() {
    return get(PLACEHOLDER);
  }
  public void setPlaceholder(String placeholder) {
      set(PLACEHOLDER, placeholder);
  }
}
Note
The default value used in all PropertyDescriptors methods should match the value in the browser when the attribute or property is NOT set. Otherwise, when the user sets the value to the default value, the value will not be correctly sent to the browser.