(Solution for angular 2, for angular 4, use ng-If / Else)
Assuming links appear on the app.component home page, follow these steps in app.component.ts. This successfully displays the "Logout" link when a user logs in, otherwise the "Logon" link is displayed ( due to binding to the observed, not the static field )
public isUserLoggedIn: boolean = false; ngOnInit(): void {
In html use this
<div> <table *ngIf="isUserLoggedIn"> <tr> <td> <a href="#" (click)="logoutClicked($event)" id="logout"><span class="glyphicon glyphicon-log-out" aria-hidden="true"></span> Logout</a><br /></td> </tr> </table> <table *ngIf="! isUserLoggedIn"> <tr> <td> <a [routerLink]="['/login']" id="login"><span class="glyphicon glyphicon-log-in" aria-hidden="true"></span>Login</a><br /></td> </tr> </table> </div>
The logoutClicked event will simply call the authService logout method
To avoid using the same method at the same time, ngSwitch is the best choice, but somehow unable to make it work, although it will look like this: -
<div [ngSwitch]="IsUserLoggedIn()"> <a href="#" (click)="logoutClicked($event)" id="logout" *ngSwitchCase="true"> <span class="glyphicon glyphicon-log-out" aria-hidden="true"></span> Logout</a><br /> <a [routerLink]="['/login']" id="login" *ngSwitchCase="false"> <span class="glyphicon glyphicon-log-in" aria-hidden="true"></span>Login</a> </div>
Nitin source share