I am developing an application which is separated in multiple modules, which are lazy-loaded. On each module:
<router-outlet>
that loads the corresponding component, according to the current route.I would like to have access, from that base component, to all of the child routes that correspond to the module, and their "data" attributes.
Here is a simple example. You can see it live on this StackBlitz.
app.component.html
<router-outlet></router-outlet>
app-routing.module.ts
const routes: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: 'general'
},
{
path: 'films',
loadChildren: './films/films.module#FilmsModule'
},
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule { }
films.component.ts
@Component({
selector: 'app-films',
templateUrl: './films.component.html',
styleUrls: ['./films.component.css']
})
export class FilmsComponent implements OnInit {
constructor() { }
ngOnInit() {
// I'd like to have access to the routes here
}
}
films.component.html
<p>Some other component here that uses the information from the routes</p>
<router-outlet></router-outlet>
films-routing.module.ts
const filmRoutes: Routes = [
{
path: '',
component: FilmsComponent,
children: [
{ path: '', pathMatch: 'full', redirectTo: 'action' },
{ path: 'action',
component: ActionComponent,
data: { name: 'Action' } // <-- I need this information in FilmsComponent
},
{
path: 'drama',
component: DramaComponent,
data: { name: 'Drama' } // <-- I need this information in FilmsComponent
},
]
},
];
@NgModule({
imports: [
RouterModule.forChild(filmRoutes)
],
exports: [
RouterModule
],
})
export class FilmsRoutingModule { }
Is there any way to get the data attributes of the child routes from within a component on the same module?
I've tried injecting Router
and ActivatedRoute
into the component but none of these seem to have the information I need.
try this
constructor(private route: ActivatedRoute) {
console.log(this.route.routeConfig.children);
}