Home > OS >  IF and ElseIF condition in Angular 13
IF and ElseIF condition in Angular 13

Time:02-23

I want to hide the Portfolio and Orders menu.

I succeeded to hide the Portfolio menu with ngIf.

    <ul  *ngIf="menu.route !== '/portfolio'  || (currentPortfolio$ | async)">

My question is, how should I hide /orders with an ElseIf?

    <ul  *ngIf="menu.route !== '/portfolio'  || (currentPortfolio$ | async)" ????>

I don't quite understand, HTML and Angular syntax...


    <ng-container *ngFor="let menu of menus; let i = index">
    <ul  *ngIf="menu.route !== '/portfolio'  || (currentPortfolio$ | async)">
    <li [ngClass]="{ selected: selectedTab === menu.route }">
       <a routerLink="{{ menu.route }}" routerLinkActive="active" (click)="toggleMenu(i); selectedTab = menu.route">
       <i ></i>
       <span > {{ menu.item }} </span>
       <i  *ngIf="selectedTab !== menu.route || !showSubmenu[i]"></i>
       <i  *ngIf="selectedTab === menu.route && showSubmenu[i]"></i>
       </a>
    </li>

EDIT

<ng-container *ngFor="let menu of menus; let i = index">
   <ul  *ngIf="menu.route !== '/portfolio'  || (currentPortfolio$ | async); else elseBlock">
      <li [ngClass]="{ selected: selectedTab === menu.route }">
         <a routerLink="{{ menu.route }}" routerLinkActive="active" (click)="toggleMenu(i); selectedTab = menu.route">
         <i ></i>
         <span > {{ menu.item }} </span>
         <i  *ngIf="selectedTab !== menu.route || !showSubmenu[i]"></i>
         <i  *ngIf="selectedTab === menu.route && showSubmenu[i]"></i>
         </a>
      </li>
      <ng-container *ngFor="let submenu of menu.submenus; let j = index">
         <li *ngIf="showSubmenu[i]">
            <a routerLink="{{ submenu.route }}">
            <i ></i>
            <span > {{ submenu.item }} </span>
            </a>
         </li>
      </ng-container>
      <li >
         <a href="#" (click)="logoff() ">
         <i ></i>
         <span >Log out</span>
         </a>
      </li>
   </ul>
   <ng-template #elseBlock>
      <ul  *ngIf="menu.route !== '/orders'  || (currentPortfolio$ | async)">
      </ul>
   </ng-template>
</ng-container>

CodePudding user response:

You can render the alternative template ng-template using the else, like the following:

<ul
  
  *ngIf="
    menu.route !== '/portfolio' || (currentPortfolio$ | async);
    else elseBlock
  "
>
  <!-- ... -->
</ul>
<ng-template #elseBlock>
  <ul>
    <!-- ... -->
  </ul>
</ng-template>

Read more about showing an alternative template using else here: https://angular.io/api/common/NgIf#showing-an-alternative-template-using-else

  • Related