given such a template
<a *ngIf="canAccess()" routerLink="/adminUsers">...</a>
<a *ngIf="canAccess()" routerLink="/link2">...</a>
<a *ngIf="canAccess()" routerLink="/otherlink">...</a>
<a *ngIf="canAccess()" routerLink="/somthingelse">...</a>
and a function:
canAccess()
{
...
how do I get
thanks
Update your template
<a *ngIf="canAccess($event)" routerLink="/adminUsers">...</a>
and your component
canAccess(event){
console.log(event.currentTarget);
console.log(event.currentTarget.getAttribute("routerlink"));
..
}
You might need:
Put the ones you need into the constructor and call their methods in your canAccess().
In addition you could protect your route (from routerLink) itself with a Guard.
My solution was to create a directive and it's associated component, so I just give it the module the user wants to access
that directive asks a service if user is logged and can access that link
if yes, the link is remplaced with the component
here is an exemple on how to insert component dynamicaly (not containing the authorization part)
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();
}
}
might be overkill, but in the end I use
<a *menuItem="dashBoard"></a>
instead of
<a class="menuItemA menuRouterLinkA" routerLink="/dashBoard" routerLinkActive="menuCurrentLinkA" >{{ "DashBoard" }}</a>
and it deals with features/page/modules.. access authorisation :-)
yay