Angular 2- using *ngIf with multiple conditions

Shakir Jameel picture Shakir Jameel · Mar 25, 2017 · Viewed 75.8k times · Source

I'm unable to selectively display links on my nav-bar. Based on who logs in (user or admin), I want to change which link shows on my nav-bar.

Below is the code for one such instance where the user/admin logs out.

In navbar.component.html -

<li *ngIf="authService.userLoggedIn()== true && authService.adminLoggedIn() == false" 
       [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}"> 
  <a (click)="onUserLogoutClick()" href="#">Logout</a>
</li>

<li *ngIf="(authService.adminLoggedIn() == true) && (authService.userLoggedIn() == false)" 
      [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
   <a (click)="onAdminLogoutClick()" href="#">Logout</a>
</li>

Both authService.adminLoggedIn() and authService.userLoggedIn() return tokenNotExpired;

Below is the relevant code in the navbar.component.ts -

 onUserLogoutClick() {
   this.authService.userLogout();
   this.flashMessage.show('You are now logged out', {cssClass: 'alert-success', timeout: 3000});
   this.router.navigate(['/login']);
   return false;   
 }

 onAdminLogoutClick() {
   this.authService.adminLogout();
   this.flashMessage.show('Administrator now logged out', {cssClass: 'alert-success', timeout: 3000});
   this.router.navigate(['/admin']);
   return false;   
 }

The authService.adminLogout() and authService.userLogout() just clears the token stored in local storage.

I apologize in advance if the mistake that I've made is silly. I'm new to Angular.

Answer

Aravind picture Aravind · Mar 25, 2017

You can move these multiline conditions and complex conditions to your component method as below

showLogout(){
    if(this.authService.userLoggedIn()== true && this.authService.adminLoggedIn() == false)
        return true;
    else
        return false;
}

Also, as the angular4 has *ngIf and else you can use it as

 <div *ngIf="showLogout();then userLogout else adminlogout"></div>

<ng-template #userLogout><a (click)="onUserLogoutClick()" href="#">Logout</a></li></ng-template>
<ng-template #adminlogout><a (click)="onAdminLogoutClick()" href="#">Logout</a></li></ng-template>