re-hide conditional shiny output once it has been rendered

↘锁芯ラ 提交于 2020-02-04 22:59:11

问题


I need some help as to how to re-hide a shiny output once it has been rendered. Below I have provided a reproducible example to explain my question.

I want text 2.2 to only be shown if Option 1 and B are selected, and text 1 to only show when option 2 is selected. I have done this by including conditionalPanel() with the conditions set accordingly.

This works, however, once the text has been rendered this text will not disappear when the input changes. I want text 2.2 to disappear if the user then changes the inputs to select any other option i.e. chooses Option 2.

Is it possible to do this with shiny? Apologies if this has been asked before - I couldn't find anything through searching - your help is much appreciated!

library(shiny)

ui <- fluidPage(
  sidebarPanel(
    selectInput("Input1", label = "Input1", choices = c("Option 1", "Option 2") ),
    conditionalPanel(condition = "input.Input1 == 'Option 1'",
                     selectInput("Input2", label = "Input2",
                                 choices = c("A", "B"))),
  ),

  mainPanel(
    tabsetPanel(
      tabPanel("Tab 1", textOutput(outputId = "text1")),

      tabPanel("Tab 2", textOutput(outputId = "text2.1"), textOutput(outputId = "text2.2") )
    )
  )


)

server <- function(input, output) {

  observe({if(input$Input1 == 'Option 2'){
    output$text1 <- renderText("This text only shows for option 2")
  }})


  output$text2.1 <- renderText("some text")

  observe({if(input$Input2 == 'B'){
    output$text2.2 <- renderText("Show this only if option 1B is selected")
  }})


} 

shinyApp(ui, server)

回答1:


You need to specify the different if possiblities inside the observe environment. Here's a solution:

library(shiny)

ui <- fluidPage(
  sidebarPanel(
    selectInput("Input1", label = "Input1", choices = c("Option 1", "Option 2") ),
    conditionalPanel(condition = "input.Input1 == 'Option 1'",
                     selectInput("Input2", label = "Input2",
                                 choices = c("A", "B"))),
  ),

  mainPanel(
    tabsetPanel(
      tabPanel("Tab 1", textOutput(outputId = "text1")),

      tabPanel("Tab 2", textOutput(outputId = "text2.1"), textOutput(outputId = "text2.2") )
    )
  )


)

server <- function(input, output) {

  observe({
    if(input$Input1 == 'Option 2'){
      output$text1 <- renderText("This text only shows for option 2")
      }
    else {
      output$text1 <- renderText("")
    }
    })


  output$text2.1 <- renderText("some text")

  observe({
    if (input$Input2 == "B") {
      output$text2.2 <- renderText("Show this only if option 1B is selected")
    }
    else {
      output$text2.2 <- renderText("")
    }
  })


} 

shinyApp(ui, server)


来源:https://stackoverflow.com/questions/59179865/re-hide-conditional-shiny-output-once-it-has-been-rendered

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!