Angular中使用两个布尔状态控制ngClass类的添加与移除
方案1:调整is-active的判定逻辑(最推荐)
因为你提到默认状态就等于is-removed的效果,所以完全不需要额外声明is-removed类,直接给is-active加优先级判断即可:state1生效的前提是state2不为true。
代码示例:
<div [ngClass]="{'is-active': state1 && !state2}"></div>
对应逻辑说明:
- state1 = true、state2 = false:添加
is-active类 - 其余所有场景(state2为true,或两个状态都为false):不添加
is-active类,保持默认状态,完全符合需求。
方案2:保留is-removed类的场景适配
如果后续需要针对is-removed做单独样式定制,需要保留这个类的声明,只需给两个类都加上互斥判断即可:
<div [ngClass]="{ 'is-active': state1 && !state2, 'is-removed': state2 }"></div>
该写法下两个类永远不会同时出现,state2为true时强制隐藏is-active、显示is-removed。
方案3:类绑定语法简化写法
也可以用Angular提供的单个类绑定语法,逻辑更直观:
<div [class.is-active]="state1 && !state2"></div>
内容的提问来源于stack exchange,提问作者Denver Dang
相关产品推荐
相关产品推荐

