Reputation: 674
I have a shiny app in which I have a selectizeInput. Only having exactly one choice is valid, but it should be possible to delete the input, so one can start typing in order to search through all choices. Only when the user has selected a new option, shiny should be informed about that. In case the user selects no new choice (leaves the selectizeInput blank and clicks somewhere else), the old unchanged choice should be restored.
I would claim that this behaviour is pretty natural. Is there a way to achieve this?
Here is an app which shows how this could be useful: I always want to have a plot with a title and never a plot without a title:
library(shiny)
library(ggplot2)
ui <- fluidPage(
selectizeInput("plottitle", "plot title", choices = letters, multiple=TRUE, options = list(maxItems = 1, minItems = 1)),
plotOutput("po")
)
server <- function(input, output, session) {
output$po <- renderPlot({
ggplot(iris) + geom_point(aes(x=Sepal.Length, y=Sepal.Width)) + ggtitle(input$plottitle)
})
}
shinyApp(ui, server)
Note that minItems = 1 does not work, maybe there is something else I could do?
Upvotes: 0
Views: 73
Reputation: 2505
The goal here is to prevent the reactivity when input$plottitle
is empty. To do so, I am conditionally modifying the plot only when input$plottitle
is not empty, so the plot never has no title.
The only situation that doesn't have a plot with a title is at the launch of the app: there is no plot at all until the user select a title.
library(shiny)
library(ggplot2)
ui <- fluidPage(
selectizeInput("plottitle", "plot title", choices = letters, multiple=TRUE, options = list(maxItems = 1, minItems = 1)),
plotOutput("po")
)
server <- function(input, output, session) {
#Initialise a reactiveValues() to store the plot. (Note: you could also you a simple reactive())
rv <- reactiveValues()
# Fill rv$plot with the plot only if input$plottitle has a value
observeEvent(input$plottitle, {
rv$plot <- ggplot(iris) + geom_point(aes(x=Sepal.Length, y=Sepal.Width)) + ggtitle(input$plottitle)
})
#Finally, the plot
output$po <- renderPlot({
rv$plot
})
}
shinyApp(ui, server)
Upvotes: 0