给定这样的模板
<a *ngIf="canAccess()" routerLink="/adminUsers">...</a>
<a *ngIf="canAccess()" routerLink="/link2">...</a>
<a *ngIf="canAccess()" routerLink="/otherlink">...</a>
<a *ngIf="canAccess()" routerLink="/somthingelse">...</a>
和一个函数:
canAccess()
{
...
我如何获得
- 路由器链接
- 该功能中的任何其他标签属性
谢谢
更新模板
<a *ngIf="canAccess($event)" routerLink="/adminUsers">...</a>
和您的组件
canAccess(event){
console.log(event.currentTarget);
console.log(event.currentTarget.getAttribute("routerlink"));
..
}
您可能需要:
- 获得当前URL的位置。
- urlSeggment如果要检查URL参数。
将您需要的内容放入构造函数中,并在canAccess()
中调用其方法。
另外,您可以使用警卫保护自己的路线(免受routerLink
(的保护。
我的解决方案是创建一个指令,并且是关联的组件,所以我只给它用户想要访问
的模块该指令询问服务是否已记录并可以访问该链接
如果是的,则该链接将用组件
重新安置这是关于如何插入组件动态的一个典范(不包含授权部分(
import { Directive, Input, ComponentFactoryResolver,ViewContainerRef } from '@angular/core';
import { MenuItemComponent } from './menuItem.component';
@Directive({ selector: '[menuItem]' })
export class MenuItemDirective {
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private viewContainer: ViewContainerRef) {}
@Input() set menuItem(_link: string) {
if(some sort of condition depending on a auth service)
{
const factory = this.componentFactoryResolver.resolveComponentFactory(MenuItemComponent);
const menuItemComponentRef = this.viewContainer.createComponent(factory);
menuItemComponentRef.changeDetectorRef.detectChanges();
}
else
this.viewContainer.clear();
}
}
可能是过分的,但最后我使用
<a *menuItem="dashBoard"></a>
而不是
<a class="menuItemA menuRouterLinkA" routerLink="/dashBoard" routerLinkActive="menuCurrentLinkA" >{{ "DashBoard" }}</a>
它处理功能/页面/模块..访问授权: - (
yay