Answer the question
In order to leave comments, you need to log in
Angular2: Is it possible to generate a navigation menu based on routing?
Good day,
Such a situation, in my routing in data roles are registered (the roles of users who can access this page)
Everything works fine, but I ran into a question about the navigation menu. For now, it's static. Is it possible to form a navigation menu directly on the basis of routing?
For example, this routing:
export const routes: Routes = [
{path: 'test1', component: Test1Component, data: {title: 'Тест 1', role: ['admin', 'user']}},
{path: 'test2', component: Test2Component, data: {title: 'Тест 2' role: ['admin']}},
{path: 'test3', component: Test3Component, data: {title: 'Тест 3' role: ['admin', 'user']}},
{path: 'test4', component: Test4Component, data: {title: 'Тест 4' role: ['admin']}},
];
Answer the question
In order to leave comments, you need to log in
I don't know how correct this is. But I did))
In general, like this ... We have such a routing (naturally invented):
export const routes: Routes = [
{path: 'test1', component: Test1Component, data: {title: 'Тест 1', roles: ['admin', 'user']}},
{path: 'test2', component: Test2Component, children: [
{path: 'test5', component: Test5Component, data: {title: 'Тест 5', roles: ['admin', 'user'}},
{path: 'test6', component: Test6Component, data: {title: 'Тест 6', roles: ['admin'}},
]},
{path: 'test3', component: Test3Component, data: {title: 'Тест 3' roles: ['admin', 'user']}},
{path: 'test4', component: Test4Component, data: {title: 'Тест 4' roles: ['admin']}},
];
menuNavigation = [];
routing: Array<Object>;
constructor(private router: Router) {
this.routing = router.config;
}
ngOnInit() {
this.buildMenuNavigation(this.routing);
}
buildMenuNavigation(navigation: Array<Object>, parentUrl: string = ''): void {
for (let nav of navigation) {
// Если есть дочерние пункты, прогоняем еще раз
if (nav['children']) {
let newParentUrl = '/' + nav['path'];
this.buildMenuNavigation(nav['children'], newParentUrl);
}
// Добавляем пункты в которых есть 'data: {}'
if (!nav['children'] && nav['data']) {
this.menuNavigation.push({
url: parentUrl + '/' + nav['path'],
title: nav['data']['title'],
roles: nav['data']['roles'],
});
}
}
}
<ng-container *ngFor="let nav of menuNavigation">
<template [hasRole]="nav.roles">
<li routerLinkActive="active">
<a [routerLink]="nav.url"><span>{{nav.title}}</span></a>
</li>
</template>
</ng-container>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question