This is a conceptional question on how to implement the required functionality the "right" way with Angular 2.
My application has a navigation menu, a toolbar, and a content area. The latter contains the primary <router-outlet>
and displays the different views like list and details.
What I want to achieve is that the toolbar is displaying different components, depending on the component/view that is rendered in the content area. For example, the list component needs a search control in the toolbar, while the details component needs a save button.
A) My first attempt was to add another (named) <router-outlet>
to the toolbar and display the toolbar components based on static routes. What feels wrong about this:
- The static content-toolbar relation is coupled too loosely for my taste.
- The relation is visible (and changeable) in the URL.
- The toolbar outlet keeps this path even if the user navigates away.
B) My second attempt was to navigate imperatively to the toolbar components (also using the named toolbar outlet) in the main view component's ngOnInit
, which couples it more tightly. What smells bad:
- A2
- A3, to prevent this I could "clear" the toolbar outlet on
ngOnDestroy
, but I haven't found out how.
C) Giving the router a last chance, since I found out that this kind-of works:
const ROUTES: Routes = [
{path: "buildings", children: [
{path: "", component: BuildingListComponent, pathMatch: "full", outlet: "primary"},
{path: "", component: BuildingListToolbarComponent, pathMatch: "full", outlet: "toolbar"},
{path: ":id", component: BuildingDashboardComponent, outlet: "primary"}
]}
];
The idea is that the router would pick the matching path per outlet. But (nooo, it could have been so easy) unfortunately, this doesn't work:
const ROUTES: Routes = [
{path: "buildings", children: [
{path: "list", component: BuildingListComponent, pathMatch: "full", outlet: "primary"},
{path: "list", component: BuildingListToolbarComponent, pathMatch: "full", outlet: "toolbar"},
{path: ":id", component: BuildingDashboardComponent, outlet: "primary"}
]}
];
It appearently (and maybe accidentially) only works with an empty path. Why, oh why?
D) A complete different strategy would be to rework my component hierarchy, so that every main view component contains a appropriate toolbar, and use multi-slot content projection. Haven't tried this, but I'm afraid running into problems with multiple instances of the toolbar.
As sometimes, this seems to be a common use case, and I'm wondering how Angular 2 experts would solve this. Any ideas?
data
to routes to configure at route level what component should be added like demonstrated in stackoverflow.com/questions/38644314/… – Günter Zöchbauer