I have a route called Customer Which is used to create New Customers. I have route link placed in different components. I have a guard in route config which is not to allow unauthorized users to create customers.
But I want to hide the Route link to unauthorized users. I don't want to check whether the user is authorized or not and then hide the link in every component. What is the best approach in hiding the route links from the single component?
Ultimately each component controls what is displayed in its template. For example, your Customer Component cannot control whether the routerLink
for its route is displayed in any other component.
What I do for handling situations like you are describing is using a service that can check authentication. I would create an AuthenticationService that handles everything related to authentication and authorization. Then create a public function on that service to check authenticatin/authorization that returns a boolean.
Then inject that service in the constructor of wherever you want to use it:
constructor(private authSvc: AuthService){}
And use it in the template to show/hide anything:
<a *ngIf="authSvc.IsAuthorized('somePermission')" [routerLink]="..."
Obviously, using a CanActivate guard is still your best protection to guard against a user accessing a route they shouldn't be able to.