Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there elseIf in Angular 4

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?

like image 947
Ankit Raonka Avatar asked Aug 02 '17 14:08

Ankit Raonka


People also ask

What is ngIf else in Angular?

NgIflink. A structural directive that conditionally includes a template based on the value of an expression coerced to Boolean. When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause.

Can ng-template have ngIf?

As the name suggests the <ng-template> is a template element that Angular uses with structural directives ( *ngIf , *ngFor , [ngSwitch] and custom directives). These template elements only work in the presence of structural directives.

Can you nest ngIf?

as long as it is a boolean (and not a call to a complicated function) there is no problem.


2 Answers

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

like image 132
yurzui Avatar answered Oct 25 '22 00:10

yurzui


No Currently elseif is not supported

Ngifelse https://angular.io/api/common/NgIf

like image 36
piyush gupta Avatar answered Oct 25 '22 02:10

piyush gupta