动态添加到闪亮用户界面的每个元素上的“删除”按钮

时间:2018-11-29 12:24:17

标签: r shiny

我正在尝试创建一个具有动态UI的闪亮应用程序,该UI添加任意数量的输入字段,每次单击操作按钮时都添加一个。创建这些新输入后,应通过单击与输入一起添加的另一个操作按钮来删除这些新输入,而不是像在问题Register event handler for dynamically added selectInput中那样,例如从列表中选择删除哪个元素。

我使用了闪亮的动态UI文章中的两个示例:https://shiny.rstudio.com/articles/dynamic-ui.html,特别是:https://gallery.shinyapps.io/insertUI/https://gallery.shinyapps.io/111-insert-ui/我不喜欢第一个示例要求您选择要使用哪个UI元素的方式。删除,然后单击以将其删除。我希望通过向每个新元素添加一个删除按钮来一键完成该操作。

基于这个堆栈溢出的问题,我编写了以下代码,使之成为一个可响应的函数,该函数可以监听多个输入:How to listen for more than one event expression within a Shiny eventReactive handler,但是显然您不能对输入对象进行切片:Getting multiple checkbox values in Shiny,我也不能弄清楚如何获得我的反应功能,确定单击了哪个删除按钮,所以我认为这种方法是死路一条。我是闪亮的反应式编程的新手,所以我不知道所有功能,我不希望有任何建议用于实现此结果的建议。

library(shiny)

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(

            actionButton('addBtn', 'Add input Set'),

            tags$div(id='inputList')
        ),
        mainPanel()
    )
)

server <- function(input, output) {

    observeEvent(input$addBtn, {
        n <- input$addBtn
        id <- paste0("input",n)
        insertUI(
            selector = '#inputList',
            ui=div(
                selectizeInput(
                    inputId = id,
                    choices = c("Stuff","to","input"),
                    selected = c("Stuff"),
                    label = "An Input:",
                    multiple = TRUE
                ),
                actionButton(paste0('removeBtn',n), 'Remove')
            )
        )
    })

    # removeModelReact <- reactive({input[grepl(pattern = "removeBtn",names(input))]},{
    #   # which button changed... and return that
    # })
    # 
    # eventReactive(removeModelReact(),{
    #   removeUI(
    #       selector = paste0('div:has(> #input',removeModelReact(),')')
    #   )
    # })
}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:1)

嗨,这应该做到。

server <- function(input, output) {

  observeEvent(input$addBtn, {
    nr <- input$addBtn
    id <- paste0("input",input$addBtn)
    insertUI(
      selector = '#inputList',
      ui=div(
        id = paste0("newInput",nr),
        selectizeInput(
          inputId = id,
          choices = c("Stuff","to","input"),
          selected = c("Stuff"),
          label = "An Input:",
          multiple = TRUE
        ),
        actionButton(paste0('removeBtn',nr), 'Remove')
      )
    )
    observeEvent(input[[paste0('removeBtn',nr)]],{
      shiny::removeUI(
        selector = paste0("#newInput",nr)
      )
    })
  })

您快到了,我刚刚添加了一个观察者,该监听器将监听remove按钮,并添加了remove UI。我还向insertUI的div中添加了一个ID,以使其以后更轻松地将其删除。

希望这会有所帮助!