在R Shiny中检测到selectInput值更改为NULL

问题描述 投票:0回答:1

在下面的代码中,我无法检测到selectInput的值更改为NULL

library(shiny)
ui <- fluidPage(
  selectInput(
    inputId = "var",
    label = "Select a variable:",
    choices = c("A", "B", "C"),
    selected = NULL,
    multiple = T),
  textOutput("selected_var")
)
server <- function(input, output) {
  observeEvent(input$var, {
    showNotification("var changed")
    output$selected_var <- renderPrint(paste0("selected var: ", input$var))
    if(is.null(input$var)) {                          # I want to be able to
      showNotification("var changed to null")         # detect this action
    }
  })
}
shinyApp(ui = ui, server = server)

如果用户选择A,然后按退格键将其删除,则我希望能够检测到该动作。

如何检测input$var的值更改为NULL

r shiny shinydashboard shiny-reactivity
1个回答
0
投票

默认情况下observeEvent设置为忽略NULL。将ignoreNULL = FALSE添加到observeEvent将解决此问题。您可能还希望添加ignoreInit = TRUE以阻止启动时触发observeEvent

这里是完整的代码:

library(shiny)

ui <- fluidPage(

    selectInput(inputId = "var", label = "Select a variable:", choices = c("A", "B", "C"), selected = NULL, multiple = T),

    textOutput("selected_var")

)

server <- function(input, output) {

    observeEvent(input$var, {

        if(is.null(input$var)) {    

            showNotification("var changed to null")    

        }

    }, ignoreInit = TRUE, ignoreNULL = FALSE)

}
shinyApp(ui = ui, server = server)
© www.soinside.com 2019 - 2024. All rights reserved.