Using API Helpers for Defining Component Properties

The framework provides a helper called PropertyDescriptor which makes managing attributes and properties in a component easy. You can use PropertyDescriptor to define the property name and the default value in a single place and use the descriptor from the setter and getter methods:

@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);
  }
}

In your component API for a given property, e.g. value of an input field, you want to ensure a couple of things are always true:

  • The getter and setter use the same property or attribute

  • The default value is handled properly

  • The getter return value is either the type used by the setter, e.g. String for an input value or an optional version of it, i.e. Optional<String> if the property is not mandatory.

PropertyDescriptors will automatically take these points into consideration for you.

PropertyDescriptor instances are created using the helpers available in the PropertyDescriptors class. There are different helper methods depending on how you want your property to work:

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

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

  • PropertyDescriptors.optionalAttributeWithDefault for mapping to an element attribute with a given default value but returning an empty Optional when the default value is set

You can use the optionalAttributeWithDefault e.g. for a placeholder in a TextField as the placeholder is not mandatory:

@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 the PropertyDescriptors methods should match what the value becomes in the browser when the attribute or property is not set. Otherwise the value will not be correctly sent to the browser when the user sets the value to the default value.