I'm currently working on an Angular application that utilizes routing and auth guards.
Check out the code on StackBlitz
View the app component HTML here
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
<ul class="nav nav-tabs">
<li role="presentation" routerLinkActive="active"
[routerLinkActiveOptions]="{exact:true}"><a routerLink="/">Home</a></li>
<li role="presentation" routerLinkActive="active"><a routerLink="/servers">Servers</a></li>
<div *ngIf="showUser">
<li role="presentation" routerLinkActive="active"><a routerLink="/users">Users</a></li>
</div>
</ul>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
<router-outlet></router-outlet>
</div>
</div>
The code above includes an if condition to control the visibility of a tab:
<div *ngIf="showUser">
<li role="presentation" routerLinkActive="active"><a routerLink="/users">Users</a></li>
</div>
This tab will only be shown if the variable showUser
is true. Otherwise, it will not appear in the home page.
Check out the TypeScript file (TS) here:
export class AppComponent{
showUser : boolean = true;
ngOnInit() {
this.showUser = false;
}
}
In this example, I've manually set this.showUser
as false. In a real-world application, this value would typically depend on certain conditions, like:
ngOnInit() {
let user = this.localStorage.getItem('user');
if(user.value == null || user.value == undefined) {
this.showUser = false;
}
}
Therefore, the user menu will only display if the condition is true.
However, there is an issue where changing the URL to include /users leads to a redirection to the users page:
https://routing-angular-bjbjqd.stackblitz.io/users
My goal is to prevent this from happening unless the showUser
condition is met.
How can I ensure that the URL does not change unless showUser
is true?