Angular 2- using *ngIf with multiple conditions

前端 未结 3 1540
被撕碎了的回忆
被撕碎了的回忆 2021-02-18 16:12

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 on

相关标签:
3条回答
  • 2021-02-18 16:49

    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>
    
    0 讨论(0)
  • 2021-02-18 16:59

    authService.userLoggedIn() or authService.adminLoggedIn() in your expression wouldn't keep your template informed about who is logged in as your function is invoked only once.

    Try make them getter in your service:

      get userLoggedIn(): boolean {
        return this.who.user; // your logic
      }
    

    Then in your template:

    <li *ngIf="authService.userLoggedIn && !authService.adminLoggedIn"...
    
    0 讨论(0)
  • 2021-02-18 17:05

    I think should be create a boolean properties in component and using it. In stead of writing function or complex expression in template. Function in template reduce performance. Complex expression make it not readble and maintainable.

    0 讨论(0)
提交回复
热议问题