You need to enable JavaScript to run this app. Angular中*ngIf生效异常,布尔值变更后对应HTML标签未重新渲染
优惠活动
大模型
产品
解决方案
定价
更多

Angular中*ngIf生效异常,布尔值变更后对应HTML标签未重新渲染

根本原因

问题出在单选按钮传递的值类型不匹配:
你在mat-radio-button上直接写的value="true"和value="false"属于HTML原生属性赋值,传递出来的$event.value是字符串类型的"true"和"false",不是你预期的布尔值。
触发异常的逻辑是:

  • 第一次切换到「One way」时,你把字符串"false"赋值给Roundtrip变量,此时执行*ngIf='Roundtrip == true'判断,字符串"false"和布尔值true做双等比较结果为false,表单隐藏,刚好符合你的预期。
  • 切回「Roundtrip」时,你把字符串"true"赋值给Roundtrip变量,按照JS双等比较的类型转换规则,字符串"true"转数字为NaN,布尔值true转数字为1,二者比较结果为false,因此表单一直不会显示。

修复方案

任选一种即可:

方案1:绑定布尔类型值

给value加方括号做Angular属性绑定,直接传递布尔值:

<mat-radio-group >
  <mat-radio-button (change)='itIsRoundtrip($event.value)' class="example-margin" checked [value]="true">Roundtrip</mat-radio-button>
  <mat-radio-button (change)='itIsRoundtrip($event.value)' class="example-margin" [value]="false">One way</mat-radio-button>
</mat-radio-group>

方案2:赋值时做类型转换

在处理函数里统一把传入的值转为布尔类型:

Roundtrip: boolean = true;

itIsRoundtrip(Roundtrip: string | boolean){
  this.Roundtrip = Roundtrip === 'true' || Roundtrip === true
  console.log(this.Roundtrip)
}

另外建议把*ngIf='Roundtrip == true'简化为*ngIf='Roundtrip',可以避免多余的类型比较坑。


内容的提问来源于stack exchange,提问作者snir.hak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 18:57:03