Last active
May 22, 2024 07:26
-
-
Save TatuLund/c01ffca58869754ea6b419b8c2cbc03b to your computer and use it in GitHub Desktop.
In Vaadin 23/24 regular ComboBox does not support scroll selected item into view. But with some JavaScript workaround this is possible to do with ComboBoxLight add-on from Directory as unlike ComboBox, ComboBoxLight does not lazy load and hence the target item is in the DOM always.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.application.views; | |
// See: https://github.com/vaadin/flow-components/issues/3470 | |
import java.util.stream.Collectors; | |
import java.util.stream.IntStream; | |
import org.vaadin.addons.componentfactory.ComboBoxLight; | |
import com.vaadin.flow.component.Html; | |
import com.vaadin.flow.component.combobox.ComboBox; | |
import com.vaadin.flow.component.html.Div; | |
import com.vaadin.flow.data.renderer.ComponentRenderer; | |
import com.vaadin.flow.router.Route; | |
@Route(value = "scroll-into-view", layout = MainLayout.class) | |
public class ComboBoxScrollIntoView extends Div { | |
public ComboBoxScrollIntoView() { | |
ComboBoxLight<String> combo = new ComboBoxLight<>(); | |
var items = IntStream.range(1, 1000).mapToObj(i -> "Value " + i) | |
.collect(Collectors.toList()); | |
combo.setItems(items); | |
combo.getElement().executeJs( | |
""" | |
$0.addEventListener('opened-changed', (e) => setTimeout(() => { | |
$0._scrollIntoView($0.items.indexOf($0._scroller.selectedItem)); | |
}, 100));""", | |
combo.getElement()); | |
combo.setItems(items); | |
combo.setRenderer(new ComponentRenderer<Html, String>(i -> new Html( | |
"<span style='color: red; font-weight: 700;'><vaadin-icon class='mr-xs' style='fill:blue' icon='vaadin:vaadin-h'></vaadin-icon>" | |
+ i + "</span>"))); | |
add(combo); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment