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?
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.
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.
as long as it is a boolean (and not a call to a complicated function) there is no problem.
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
No Currently elseif is not supported
Ngifelse https://angular.io/api/common/NgIf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With