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

Angular中两条件任一成立时隐藏元素,*ngIf写法不生效如何解决?

修复方案

1. 修正判断逻辑

你当前的*ngIf写法是两个条件任意成立时显示对应元素,和你要的「条件成立时隐藏」逻辑完全相反,加取反符调整逻辑即可:

<!-- 取反原逻辑即可实现条件成立时隐藏 -->
<div class="row" *ngIf="!(productID == category.Lane || productID == category.Val)">

<!-- 也可以写成更易读的等效写法 -->
<div class="row" *ngIf="productID !== category.Lane && productID !== category.Val">

2. 解决类型不匹配问题

你当前ng-option用的value="{{ product.id }}"插值写法会强制把product.id转为字符串类型,如果category.Lane/category.Val是数字类型,就算数值相等也会出现判断失效的问题,改成方括号绑定value保留原始数据类型:

<ng-option 
  *ngFor="let product of products | orderBy: 'name'" 
  [value]="product.id"
>
  {{ product.name }}
</ng-option>

3. 修复表单属性混用冲突

你同时给ng-select设置了formControlName(响应式表单属性)和[(ngModel)](模板驱动表单属性),Angular高版本默认禁止这种混用,会导致productID变量值更新不及时,按你使用的表单模式二选一即可:

  • 用响应式表单:删除[(ngModel)]="productID",直接取表单控件的值做判断
    // 组件ts中新增getter简化模板调用
    get selectedProductId() {
      return this.你的表单实例名.get('productId').value
    }
    
    <div class="row" *ngIf="selectedProductId !== category.Lane && selectedProductId !== category.Val">
    
  • 用模板驱动表单:删除formControlName="productId"即可

如果确实需要同时使用两个属性,给ng-select加上[ngModelOptions]="{standalone: true}"即可解除冲突。


内容的提问来源于stack exchange,提问作者Allison.A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:54:05