Angular component.html 中的 3 种方式 If else 条件

Angular a 3 way If else condition in the component.html

我正在使用 Angular 12,在我的 component.html 中,我需要有 3 级条件。

例如:

我有一个列表,我需要检查它是否包含字符串。

true 和 false 状态都有不同的输出,最后我需要 ELSE 来处理任何其他情况。

所以...首先我有一个条件:

<div *ngIf="list.includes('sometext') && listitem === null ">Condition 1</div>

现在是与上述相反的条件:

<div *ngIf="!list.includes('sometext') && listitem === null ">Condition 2</div>

最后是 ELSE:

<div>Condition 3 or Any other condition from the others above</div>

我该怎么做?

解决这个问题最好的方法是使用[=h11=]代替ngIf,如下所示:

<container-element [ngSwitch]="true">
   <some-element *ngSwitchCase="list.includes('sometext') && listitem === null ">...</some-element>
   <some-element *ngSwitchCase="!list.includes('sometext') && listitem === null ">...</some-element>
   <some-element *ngSwitchDefault>Condition 3 or Any other condition from the others above</some-element>
</container-element>

嵌套的 if 语句更易于阅读。

<ng-container *ngIf="listitem === null; else third">
   <div *ngIf="list.includes('sometext')">Condition 1</div>
   <div *ngIf="!list.includes('sometext')">Condition 2</div>
</ng-container>
<ng-template #third>
   <div>Condition 3 or Any other condition from the others above</div>
</ng-template>

你可以这样实现:

<ng-container *ngIf="listitem; else noListItemTmpl">
    <div>Condition 3 or Any other condition from the others above</div>
</ng-container>

<ng-template #noListItemTmpl>
    <div *ngIf="list.includes('sometext')">Condition 1</div>
    <div *ngIf="!list.includes('sometext')">Condition 2</div>
</ng-template>

没有讨厌的 listitem === null 检查。