Using the Element API

This section demonstrates how to create a component using the Element API and a single DOM element.

import com.vaadin.flow.component.AbstractSinglePropertyField;
import com.vaadin.flow.component.Synchronize;
import com.vaadin.flow.component.Tag;

@Tag("input") (1)
public class ColorPicker extends AbstractSinglePropertyField<ColorPicker, String> { (2)

    public ColorPicker() {
        super("value", "", false); (3)

        getElement().setAttribute("type", "color"); (4)

        setSynchronizedEvent("change"); (5)
    }

}
1 Defines the root element that is created automatically by the Component class and can be accessed using the getElement() method.
2 Using AbstractSinglePropertyField as a base class which is suitable for creating components based on a single element’s property.
3 Passing the name of the element’s property that refers to the value.
4 Setting the type attribute value.
5 By default, AbstractSinglePropertyField listens to a value-changed event, but <input type=color> fires change.

After a component is implemented it can be used in views, for example:

@Autowired
private Notifications notifications;

@Subscribe
public void onInit(final InitEvent event) {
    ColorPicker colorPicker = new ColorPicker();
    getContent().add(colorPicker);

    colorPicker.addValueChangeListener(e ->
            notifications.show("Color: " + e.getValue()));
}
color picker