Is there elseIf in Angular 4

Ankit Raonka picture Ankit Raonka · Aug 2, 2017 · Viewed 12.1k times · Source

I have a number of statements

<ng-template [ngIf]="xyz== 1">First</ng-template>
<ng-template [ngIf]="pqr == 2">Second</ng-template>
<ng-template [ngIf]="abc == 3">Third</ng-template>

Multiple conditions in above statement can be true.

But what i want is, first check for first statement if true then display and leave the rest

If false, then check for second and so on

how to achieve this?

Answer

yurzui picture yurzui · Aug 2, 2017

You can try using ngIf directive like:

<ng-template [ngIf]="xyz == 1" [ngIfElse]="second">First</ng-template>
<ng-template #second>
  <ng-template [ngIf]="pqr == 2" [ngIfElse]="third">Second</ng-template>
</ng-template>
<ng-template #third>
  <ng-template [ngIf]="abc == 3">Third</ng-template>
</ng-template>

with ng-container it will look as follows:

<ng-container *ngIf="xyz == 1; else second">First</ng-container>
<ng-template #second>
    <ng-container *ngIf="pqr == 2; else third">Second</ng-container>
</ng-template>
<ng-template #third>
    <ng-container *ngIf="abc == 3">Third</ng-container>
</ng-template>

But if you want to use for loop statement i can offer the following solution:

<ng-container *ngTemplateOutlet="next; context: { $implicit: 0 }"></ng-container>

<ng-template #next let-i>
  <ng-container *ngIf="conditions[i]">
    <ng-container *ngIf="conditions[i] && conditions[i].condition(); else shift">{{ conditions[i].result }}</ng-container>
      <ng-template #shift >
        <ng-container *ngTemplateOutlet="next; context: { $implicit: i + 1 }"></ng-container>
      </ng-template>
  </ng-container>
</ng-template>

where conditions

conditions = [
  {
    condition: () => this.xyz === 1,
    result: 'First'
  },
  {
    condition: () => this.pqr === 2,
    result: 'Second'
  },
  {
    condition: () => this.abc === 3,
    result: 'Third'
  }
];

Plunker Example