Angular 2- 在多个条件下使用 *ngIf [英] Angular 2- using *ngIf with multiple conditions

查看:29
本文介绍了Angular 2- 在多个条件下使用 *ngIf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在导航栏上有选择地显示链接.根据谁登录(用户或管理员),我想更改导航栏上显示的链接.

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.

在 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>

authService.adminLoggedIn()authService.userLoggedIn() 都返回 tokenNotExpired;

下面是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;   
 }

authService.adminLogout()authService.userLogout() 只是清除存储在本地存储中的令牌.

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

如果我犯的错误很愚蠢,我提前道歉.我是 Angular 的新手.

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

推荐答案

您可以将这些多行条件和复杂条件移动到您的组件方法中,如下所示

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;
}

此外,由于 angular4 具有 *ngIf 和 else,您可以将其用作

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>

这篇关于Angular 2- 在多个条件下使用 *ngIf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆