gpt4 book ai didi

angular - Angular 4中是否有elseIf

转载 作者:太空狗 更新时间:2023-10-29 17:01:21 26 4
gpt4 key购买 nike

我有很多说法

<ng-template [ngIf]="xyz== 1">First</ng-template>
<ng-template [ngIf]="pqr == 2">Second</ng-template>
<ng-template [ngIf]="abc == 3">Third</ng-template>

上述语句中的多个条件可以为真。

但我想要的是,首先检查第一个语句是否为真,然后显示并保留其余部分

如果为假,则检查第二个等等

如何实现?

最佳答案

您可以尝试使用 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>

使用 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>

但是如果你想使用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>

where 条件

conditions = [
{
condition: () => this.xyz === 1,
result: 'First'
},
{
condition: () => this.pqr === 2,
result: 'Second'
},
{
condition: () => this.abc === 3,
result: 'Third'
}
];

Plunker Example

关于angular - Angular 4中是否有elseIf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45463191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com