问题
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.
回答1:
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>
回答2:
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"...
来源:https://stackoverflow.com/questions/43021972/angular-2-using-ngif-with-multiple-conditions