You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中使用OR运算符的多条件*ngIf指令失效问题

Angular *ngIf多条件逻辑错误修复

你的问题出在第二个*ngIf的条件逻辑上——用了||(或运算符)导致判断永远为真,所以"Show"区域会一直显示,和"Hide"区域可能同时出现,不符合预期。

错误原因分析

假设element.documentStatus的值是DELETED,那么element.documentStatus !== 'SUPERSEDED'和element.documentStatus !== 'UNDER_QC_REVIEW'这两个条件都是true,整个||连接的条件就会成立,"Show"就会显示。同理,不管documentStatus是三个值中的哪一个,另外两个!==条件都会是true,导致"Show"永远显示。

修正方案

有两种简洁的修正方式:

方式1:直接取反第一个*ngIf的条件

利用Angular的*ngIf逻辑,当第一个条件不成立时,显示"Show":

<ng-container *ngIf="(element.documentStatus === 'DELETED' || element.documentStatus === 'SUPERSEDED' || element.documentStatus === 'UNDER_QC_REVIEW')">
    Hide
</ng-container>
<ng-container *ngIf="!(element.documentStatus === 'DELETED' || element.documentStatus === 'SUPERSEDED' || element.documentStatus === 'UNDER_QC_REVIEW')">
    Show
</ng-container>

方式2:将||替换为&&(与运算符)

要显示"Show",需要同时满足不是三个状态中的任何一个,所以用&&连接所有反向条件:

<ng-container *ngIf="(element.documentStatus === 'DELETED' || element.documentStatus === 'SUPERSEDED' || element.documentStatus === 'UNDER_QC_REVIEW')">
    Hide
</ng-container>
<ng-container *ngIf="(element.documentStatus !== 'DELETED' && element.documentStatus !== 'SUPERSEDED' && element.documentStatus !== 'UNDER_QC_REVIEW')">
    Show
</ng-container>

两种方式都能实现:当文档状态是DELETED/SUPERSEDED/UNDER_QC_REVIEW时显示"Hide",否则显示"Show"。

内容的提问来源于stack exchange,提问作者Srikanth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:24:27