Reputation: 6859
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?
Upvotes: 16
Views: 13978
Reputation: 1582
Another alternative is to use *ngIf-then-else and ternary operator:
<ng-container *ngIf="isFirst; then first; else (isSecond ? second : third)"></ng-container>
<ng-template #first>First</ng-template>
<ng-template #second>Second</ng-template>
<ng-template #third>Third</ng-template>
Upvotes: 0
Reputation: 214085
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'
}
];
Upvotes: 16
Reputation: 20461
Why not just do more work in the component:
<ng-template [ngIf]="status == 'first'">First</ng-template>
<ng-template [ngIf]="status == 'second'">Second</ng-template>
<ng-template [ngIf]="status == 'third'">Third</ng-template>
in component code:
status string;
if (xyz == 1)
status = 'first';
else if (pqr == 2)
status = 'second';
else if (abc == 3)
status = 'third';
Upvotes: 2
Reputation: 71
No Currently elseif is not supported
Ngifelse https://angular.io/api/common/NgIf
Upvotes: 2