Ank*_*nka 13 angular-ng-if angular
我有一些陈述
<ng-template [ngIf]="xyz== 1">First</ng-template>
<ng-template [ngIf]="pqr == 2">Second</ng-template>
<ng-template [ngIf]="abc == 3">Third</ng-template>
Run Code Online (Sandbox Code Playgroud)
上述陈述中的多个条件都可以成立.
但我想要的是,首先检查第一个声明是否为真,然后显示并保留其余部分
如果为false,则检查第二个,依此类推
怎么实现这个?
您可以尝试使用如下ngIf指令:
<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>
Run Code Online (Sandbox Code Playgroud)
用ng-container它看起来如下:
<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>
Run Code Online (Sandbox Code Playgroud)
但是如果你想使用for循环语句,我可以提供以下解决方案:
<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>
Run Code Online (Sandbox Code Playgroud)
哪里 conditions
conditions = [
{
condition: () => this.xyz === 1,
result: 'First'
},
{
condition: () => this.pqr === 2,
result: 'Second'
},
{
condition: () => this.abc === 3,
result: 'Third'
}
];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9112 次 |
| 最近记录: |