Reputation: 3824
I have implemented my layout like the following, and I want my components (each of them is a separate route) to be inside mat-card-content. But the problem is when I try to change mat-card-title dynamically since it is not inside the router-outlet, I can not get any data. Is there any approach to achieve this? (without implementing mat-card-header inside of each component)
<mat-card>
<mat-card-header>
<mat-card-title>{{ routerTitle }}</mat-card-title>
<span>
here I want to have my router data
</span>
</mat-card-header>
<mat-card-content>
<router-outlet></router-outlet>
</mat-card-content>
</mat-card>
and this is my module routes look like:
{ path: 'dashboard', component: DashboardComponent, data: { title: 'Dashboard' } }
and this is the main app-routing:
{
path: '',
component: PanelLayoutComponent,
children: [
{
path: '',
loadChildren: () =>
import('./modules/modules.module').then(
(module) => module.ModulesModule
),
},
],
},
When I log router.snapshot.data.title
, in the parent component, I get an empty object since it is outside of router-outlet.
Upvotes: 2
Views: 3185
Reputation: 1784
As I said in the comments, you can use your service to share data, but in your case, I am not sure it's finally what you need.
From wherever you want, you can subscribe to the router
events. If you do in your component where you have your mat-card
, you can change the routerTitle
directly when route change.
On the constructor of your component, you need to create something like this
router.events.forEach(e => {
if (e instanceof NavigationEnd) {
this.title = route.root.firstChild.snapshot.data.title;
}
});
You get all the events of the router (NavigationStart, RouteConfigLoadStart, RouteConfigLoadEnd, RoutesRecognized ... here a list of all the events), and you just want to know if the navigation is done. Once it is done, you get the value you've passed on your route.
I have created a stackblitz to show you how it works
Upvotes: 3