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

Detecting a selectInput value change to NULL in R Shiny

在下面的代码中,我无法检测到 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

默认情况下 observeEvent 设置为忽略 NULL。添加 ignoreNULL = FALSEobserveEvent 将解决这个问题。您可能还希望添加 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)