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

ngx-formly多选框表达式问题:无法检测‘Other’选项选中状态

ngx-formly多选框表达式错误修复

问题原因

你遇到的报错和输入框始终显示的问题,根源有两点:

  1. 数据类型不匹配:multicheckbox组件配置了templateOptions.type: "array",所以model.what_are_your_sources_of_income是数组类型,并非键值对对象,无法通过.Other的方式判断选项是否选中。
  2. 空值未处理:该字段初始值设为null,未选择任何选项时直接访问model.what_are_your_sources_of_income.Other,会触发Cannot read properties of undefined错误。

修复方案

修改other_sources_of_income字段的expressions逻辑,改用数组的includes()方法判断是否包含"Other"值,同时先校验数组是否存在:

{
  "key": "what_are_your_sources_of_income",
  "type": "multicheckbox",
  "templateOptions": {
    "type": "array"
  },
  "props": {
    "label": "What are your sources of income?",
    "defaultValue": [], // 建议将初始值从null改为空数组,避免空值问题
    "required": true,
    "options": [
      {
        "label": "Cool stuff",
        "value": "Cool stuff"
      },
      {
        "label": "Other",
        "value": "Other"
      }
    ]
  }
},
{
  "key": "other_sources_of_income",
  "type": "input",
  "defaultValue": "",
  "props": {
    "label": "Other sources of income:",
    "placeholder": "",
    "className": "nested-field"
  },
  "expressions": {
    "hide": "!model.what_are_your_sources_of_income || !model.what_are_your_sources_of_income.includes('Other')",
    "props.required": "model.what_are_your_sources_of_income && model.what_are_your_sources_of_income.includes('Other')"
  }
}

额外建议:将what_are_your_sources_of_income的defaultValue从null改为[](空数组),初始状态下数组存在,表达式判断更流畅,也能减少潜在的空值报错。

内容的提问来源于stack exchange,提问作者DB1856

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:02:08