Angular中*ngIf多条件(与/或运算符)的正确写法咨询
正确的Angular *ngIf条件实现
先明确你的需求逻辑:
- 原逻辑:排除
activeIndex为0或2的场景,显示if块内容 - 新需求:仅排除两种场景——
activeIndex为2,或activeIndex为0且obj不是空对象;其余场景(包括activeIndex为0但obj是空对象、activeIndex为其他值)都显示if块内容
方案1:直接逻辑判断(推荐)
用清晰的正向逻辑表达式,避免多层非运算混淆:
<div class="lmn-my-0 lmn-py-0"> <ng-container *ngIf="activeIndex !== 2 && (activeIndex !== 0 || (obj && Object.keys(obj).length === 0)); else otherSteppers"> <!-- if condition some code --> </ng-container> <ng-template #otherSteppers> <!-- else some code --> </ng-template> </div>
方案2:非运算包裹排除条件(贴合原代码写法)
如果你习惯用非运算包裹需要排除的场景,逻辑等价于排除「activeIndex===2」或「activeIndex===0且obj非空」:
<div class="lmn-my-0 lmn-py-0"> <ng-container *ngIf="!(activeIndex === 2 || (activeIndex === 0 && obj && Object.keys(obj).length > 0)); else otherSteppers"> <!-- if condition some code --> </ng-container> <ng-template #otherSteppers> <!-- else some code --> </ng-template> </div>
空对象判断的注意事项
- 不推荐用
(obj | json) == '{}':管道转换会产生额外性能开销,且当obj为null或undefined时会出错 - 用
obj && Object.keys(obj).length === 0可以安全判断:确保obj存在且是无属性的空对象
你无效代码的问题
你的尝试代码!(activeIndex === 0 && (obj | json) == '{}' || activeIndex === 2)逻辑完全反向:它排除的是「activeIndex为0且obj为空」或「activeIndex为2」的场景,和你的需求正好相反。
内容的提问来源于stack exchange,提问作者Mitul Panchal
相关产品推荐
相关产品推荐

