I am having trouble with the way *ngIf works in Angular. I have a navbar component that does a check and should render different lists based on true/false response, it works properly in that regard, but after a routing to a different page it stops working until I refresh a page again.
HTML:
<div *ngIf="isUserValid(); then logged_in else logged_out"></div>
<ng-template #logged_out>
<ul class="dropdown-menu dropdown-menu-dark dropdown-menu-end" aria-labelledby="navbarDropdown">
<li>
<p class="dropdown-item">You are not logged in!</p>
</li>
<li><hr class="dropdown-divider"></li>
<li>
<a class="dropdown-item" routerLink="/login"> Login </a>
</li>
<li>
<a class="dropdown-item" routerLink="/signup"> Sign-Up </a>
</li>
</ul>
</ng-template>
<!-- If user is logged in -->
<ng-template #logged_in>
<ul class="dropdown-menu dropdown-menu-dark dropdown-menu-end" aria-labelledby="navbarDropdown">
<li>
<p class="dropdown-item">Hi, [user's name]</p>
</li>
<li><hr class="dropdown-divider"></li>
<li>
<a class="dropdown-item" (click)="quit()" routerLink="/login"> Sign-Out </a>
</li>
</ul>
</ng-template>
TS (this is what happens when quit is clicked):
quit(): void{
this.is_valid_user = false;
localStorage.clear();
this.router.navigate(['login']).then(r => console.log('user quit'));
}
isUserValid(): boolean{
return this.is_valid_user;
}
When you click on sign-out button it should redirect and show the logged-out block but it shows nothing and only does so after a page refresh. Any help is appreciated.
In angular you have to know that a component gets initialized once. A router link does not change the component's state. A full refresh starts the angular lifecycle again. So I assume your "isUserValid()" is only executed once. Could you please provide the complete typescript file? Where did you place the "isUserValid()" method?