gidravlic
gidravlic

Reputation: 114

Combobox and suffix slot

I want to add a component to ComboBox's suffix slot. Based on an old Vaadin forum topic you can do it in Vaadin 13, but it doesn't work with Vaadin 22. Is it possible to do this?

Upvotes: 2

Views: 403

Answers (2)

gidravlic
gidravlic

Reputation: 114

In order to make comments(reputation), I have to do something useful for the community.

Workaround:

 public static Div setComponentSuffix(Component target, Component component) {
        var div = new Div();
        div.getStyle()
                .set("width", "auto !important");
        div.getElement()
                .setAttribute("id", "my-id")
                .setAttribute("slot", "my-suffix")
                .setAttribute("part", "my-icon")
                .appendChild(component.getElement());
        target.getElement().appendVirtualChild(div.getElement());
        setSuffix(target, div);
        target.addAttachListener(attachEvent -> setSuffix(target, div));
        return div;
    }

    private static void setSuffix(Component target, Component suffix) {
        removeSuffix(target);
        target.getElement()
                .executeJs("const inputSlot = this.shadowRoot.querySelector('div > vaadin-input-container > slot[name=input]');"
                        + "inputSlot.parentNode.insertBefore($0, inputSlot.nextSibling);", suffix.getElement());
    }

    private static void removeSuffix(Component target) {
        target.getElement()
                .executeJs("const suffix = this.shadowRoot.querySelector('#my-id');" +
                        "if (typeof(suffix) != 'undefined' && suffix != null) {" +
                        "  suffix.remove();" +
                        "}");
    }

call

setComponentSuffix(<My field with vaadin input>, <My component suffix>);

Upvotes: 1

Tatu Lund
Tatu Lund

Reputation: 10623

There is a better example of setting components to prefix slot of the selected components in Cookbook, which works also with Vaadin 22. The JavaScript method in Forum relies on internal structure of the component that has been changed in Vaadin 22 in order to improve accessibility support.

You can modify the linked recipe to suffix slot as well, but just note that these components have their own button already in the suffix slot, so in most cases, it is not a good idea from the UX perspective to add additional components there.

Upvotes: 3

Related Questions