jupyter-notebookpanelholoviz

How to add and remove elements to/from Select in Holoviz panel dynamically?


I want to create a dynamic list with Holoviz's panel library. I want to be able to add and remove elements from this dynamic list. I use jupyter.

I have some code that has the UI and adds elements to the list. When I print the list, I can see that the elements are added to the list, however the UI does not update to display the list with the added elements.

import panel as pn

pn.extension()

text_input = pn.widgets.TextInput(placeholder='Enter text here')
add_button = pn.widgets.Button(name='Add')

item_list = pn.widgets.Select()
item_list.multiple = True

def add_item(event):
    item_list.options.append(text_input.value)
    text_input.value = ''

add_button.on_click(add_item)


def remove_items(event):
    current_selection = item_list.value
    item_list.options = [item for item in item_list.options if item != current_selection]

remove_button = pn.widgets.Button(name='Remove selected')
remove_button.on_click(remove_items)

layout = pn.Column(
    pn.Row(text_input, add_button),
    item_list,
    remove_button,
)


layout.servable()

Solution

  • You have to manually trigger an update in the UI:

    def add_item(event):
        item_list.options.append(text_input.value)
        text_input.value = ''
        item_list.param.trigger('options')
    

    Same goes for removing an item:

    def remove_items(event):
        current_selection = item_list.value
        item_list.options = [item for item in item_list.options if item != current_selection]
        item_list.param.trigger('options')