In my application I use the approach described in Erik's answer (get the parent component during onAttach
of the routed view). However I expanded it a bit and make use of interfaces to prevent duplicate code. Here's my setup:
public class MainView extends HorizontalLayout implements RouterLayout {
public MainView(){
...
}
public interface Retriever extends HasElement {
default MainView getMainView() {
Component parent = getElement().getComponent().orElse(null);
while (parent != null && !parent.getClass().equals(MainView.class)) {
parent = parent.getParent().orElse(null);
}
return (MainView)parent;
}
}
}
@Route("main")
public class MainRoute extends VerticalLayout implements MainView.Retriever {
public MainRoute(){
...
}
@Override
public void onAttach(){
MainView mainView = getMainView();
if (mainView != null){
mainView.someCode(); // do with the mainView what you want here
} else {
LOGGER.error(...);
}
}
}
please notice that my routerLayout is called MainView and not MainLayout. I did not want to change that name as the name "MainView" is used for the routerlayout in most official documentations and examples