I'm new to Angular. Currently, the login functionality of the application is working. When the user logs in, it stores the user data in the local storage. I have a navbar which has two li elements: Login and Logout. When the user is logged in, I want Logout link to be displayed but when the user is logged out, the Logout link should be disappeared and Login link should appear.
In my navbar.component.ts file, I have a function where I'm checking if the localstorage contains any value then the function should return false and the logout link shouldn't be visible anymore and when the user is not logged in then only the login link should appear.
Here's my code for navbar.component.ts:
authenticate: boolean = false;
token: any;
checkStorage(){
this.token = localStorage.getItem('user')
if(this.token === null){
this.authenticate = false;
return this.authenticate;
} else {
this.authenticate = true;
return this.authenticate;
}
}
and here's navabar.component.html:
<ul class="navbar-nav">
<li *ngIf="authenticate" class="nav-item">
<a class="nav-link" href="#" routerLinkActive="active" routerLink="/login">Login</a>
</li>
<li *ngIf="authenticate"class="nav-item">
<a class="nav-link" href="#" (click)="onLogout()">Logout</a>
</li>
</ul>
Any help would be appreciated. Thanks.
Edited: I have tried using *ngIf="!authenticate" on login yet it doesn't work. This just shows the login link on the navbar but once I'm logged in, the login link still remains there and logout link never shows up.
!
) – ChatterOne