How to hide link by guard angular2

ぃ、小莉子 提交于 2019-12-03 13:50:18

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!