Vaadin 14 combo box with nonselectable separators.

Hi all.

I was wondering if the combo boxes support nonselectable separators. We are currently migrating some of our legacy app and have used this feature in some of the combo boxes. If this feature does exist, when doing autocomplete does it skip the separators.

If this does not exist, is there a work around?

Thanks in advance.

18441542.png

Hello, here is one way of implementing the non-selectable separators in a ComboBox:

@Route("")
@CssImport(value = "./styles/vaadin-combo-box-item-styles.css", themeFor = "vaadin-combo-box-item")
public class ComboBoxBasicView extends VerticalLayout {

    public ComboBoxBasicView() {
        ComboBox<String> combo = new ComboBox<>();
        combo.setItems("Heading one", "Option one", "Option two",
                "Option three", "Heading two", "Option four", "Option five");
        combo.setRenderer(new ComponentRenderer<>(item -> {
            Span span = new Span(item);
            if (isHeading(item)) {
                span.setEnabled(false);
                span.getStyle().set("pointer-events", "none");
                span.getStyle().set("opacity", "0.5");
            } else {
                span.getStyle().set("padding-left", "10px");
                span.getStyle().set("pointer-events", "auto");
            }
            return span;
        }));
        combo.addValueChangeListener(e -> {
            if ((e.getValue() != null) && isHeading(e.getValue())) {
                if ((e.getOldValue() != null)) {
                    combo.setValue(e.getOldValue());
                } else {
                    combo.clear();
                }
            }
        });

        add(combo);
    }

    private boolean isHeading(String item) {
        return item.startsWith("Heading");
    }
}

Then in styles/vaadin-combo-box-item-styles.css you will also need the following style to disable the default selection of items:

:host {
	pointer-events: none;
}

Thank you Tarek!