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
相关产品推荐
相关产品推荐

