【问题标题】:Angular a 3 way If else condition in the component.htmlAngular 3 方式 If else 条件在 component.html
【发布时间】:2021-09-28 15:42:42
【问题描述】:

我正在使用 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>

我该怎么做?

【问题讨论】:

  • 只是一个建议,回答如下:您是否想过使用一种方法或服务来显示条件值?那你就不用担心每次有新的条件到来时添加额外的标签了吗?

标签: angular angular12


【解决方案1】:

解决这个问题最好的办法是使用ngSwitchCase insead of 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>

【讨论】:

  • 为什么?你只有 1 个 else,继续进一步添加 "else if" 案例需要嵌套模板,这看起来很脏
  • 你说过Angular ngIf doesn't support else if or something simillar...。这不是真的。如果这看起来很脏,那是个人意见。 Angular 支持else 功能。
  • 我通过明确退出“else if”来修复帖子,抱歉造成误解
  • 你又错了,你的解决方案确实非常优雅。但是将if 放入else 块中等同于执行else if
【解决方案2】:

嵌套的 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>

【讨论】:

  • 我收到一个错误...上面的代码出现了意外的结束标签
  • 错字(:已修复
【解决方案3】:

你可以这样实现它:

<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 检查。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 2019-10-20
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多