Is there more in Angular 4
I have a few 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>
Several conditions in the above statement may be true.
But what I want, first check for the first statement, if true, then display and leave the rest
If false, then check for a second, etc.
how to achieve this?
You can try using the directive ngIf, for example:
<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-containerit will look like this:
<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 a loop operator, 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'
}
];
Why not just work more 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';