Call shiny ui in a parent module and server in child module

I have a shiny application which uses nested modules. What I would like to do is call a shiny module ui in a grandparent's ui and the shiny server in the grandchild server. Here is a simple example:

library(shiny)

sub_module_b_ui <- function(id) {
  ns <- NS(id)
  sliderInput(
    inputId = ns("slider"),
    label = "my slider",
    min = 1,
    max = 100,
    value = 20,
    step = 1,
  )
}

#' @export
sub_module_b_server <- function(id) {
  moduleServer(id, function(input, output, session) {
    observeEvent(input$slider, {
      print(input$slider)
    })
  })
}

sub_module_a_server <- function(id, parent_ns) {
  moduleServer(id, function(input, output, session) {
    sub_module_b_server(id = "filters")
  })
}

main_module_ui <- function(id) {
  ns <- NS(id)
  sub_module_b_ui(id = ns("filters"))
}

#' @export
main_module_server <- function(id) {
  moduleServer(id, function(input, output, session) {
    ns <- session$ns
    sub_module_a_server(id = "sub_module_a", parent_ns = ns)
  })
}

ui <- fluidPage(
  tags$h1("My page"),
  main_module_ui(id = "main_module")
)

server <- function(input, output) {
  main_module_server(id = "main_module")
}

shinyApp(ui = ui, server = server)

To explain a bit further, this is the hierarchy:

  • Shiny application
    " --- main module"
    " ---------- sub module a"
    " ---------------- sub module b"

What I am really trying to achieve is call sub_module_b_ui inside of main_module_ui. And call sub_module_b_server inside of the sub_module_a_server. To me it does not seem related to namespaces because even when I manually type the input id:

sub_module_b_server <- function(id) {
  moduleServer(id, function(input, output, session) {
    observeEvent(input[["main_module-filters-slider"], {
      print(input$slider)
    })
  })
}

the observe even does not trigger the event.

Would appreciate anyone's help.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.