我有一个漂亮的应用程序,它可以根据用户的选择动态地删除和插入输入UI。选择choice1
和choice2
生成的UI共享了它们的部分输入字段。我想使用shinyvalidate
包来添加一些验证规则,这些规则可以应用于共享的输入。在下面的示例中,用户可以在侧边栏上进行选择。一旦做出选择,主面板上ID为“content”的div将被删除,并插入一个新的div。规则似乎起作用了,但除非我先在输入字段中键入一些内容,否则当我切换选项时,红色警告消息不会出现。
library(shiny)
library(glue)
library(shinyvalidate)
ui <- fluidPage(
sidebarPanel(
selectInput("select", label = "select", choices = c("", "choice1", "choice2"))
),
mainPanel(id = "main",
tags$div(id = "content"))
)
server <- function(input, output) {
# validate input
iv <- InputValidator$new()
iv$add_rule("input", sv_required())
iv$enable()
observeEvent(input$select, {
if(input$select == "choice1"){
removeUI("#content")
insertUI("#main", ui = tags$div(
id = "content",
textInput("input", "input")))
}
if(input$select == "choice2"){
removeUI("#content")
insertUI("#main", ui = tags$div(
id = "content",
textInput("input", "input")))
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
1条答案
按热度按时间6gpjuf901#
这是通过在
observeEvent
完成其工作后触发iv$enable
来实现的(我认为“无效”是正确的措辞)。编辑
我不知道为什么,但您必须在
removeUI
和insertUI
中设置immediate = TRUE
: