How to hide admin link in view html. I have to guard :Admin and Manager
Router config :
{
path: 'manager',
component: ManagerComponent,
canActivate: [ManagerGuard]
},
{
path: 'user',
component: UserAdminComponent,
canActivate: [AdminGuard]
}
In view :
<li>
<a routerLink="/user" routerLinkActive="active-link">User</a>
</li>
I want to hide link on /user for ManagerGuard when but show for AdminGuard.
Also if already answered in a way which might be helpful, I used here another approach. As you already have your canActivate method in the Guard, you could also inject your navigation component with that Guards and you can call these canActivate methods directly:
In your component which holds the navigation
constructor(private adminGuard: AdminGuard)
and then in the template
<li *ngIf="adminGuard.canActivate()">
<a routerLink="/user" routerLinkActive="active-link">User</a>
</li>
Edit
This does not work in prod mode in my case (if you use parameters which have to be injected). I just tried to compile it but angular complains about the missing parameters. If you do not use parameters, this works fine, or, if you do not use the parameters in your function - then simply pass
<li *ngIf="adminGuard.canActivate(null,null)">
<a routerLink="/user" routerLinkActive="active-link">User</a>
</li>
Another thing: If you is variables like the 'adminGuard' above in the template, it must be public - not private.
In my opinion this has nothing to do with the router itself.
Your Guards may call another service which has the information about which kind of user is logged in: Admin or Manager.
You should create a service that knows the type of the user. Then inject this service with Dependency Injection into your component where you have the routerLink
.
There you can ask the service and toggle the link with *ngIf
:
<li *ngIf="myService.getCurrentUser().isAdmin()">
<a routerLink="/user" routerLinkActive="active-link">User</a>
</li>
So the service provides a function that gives you the user which is currently logged in and the isAdmin()
-function of the user returns true
or false
. If the user is admin then the <li>
will be shown, otherwise it will be hidden.
This is just an example but I hope you get the point. It has more to do with basic functionality of Angular 2 rather than the router of Angular 2. More information about *ngIf
can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With