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

Ionic动态加载子分类输入框绑定数组ngModel报错及存储问题

问题根因

你遇到的Cannot read properties of undefined (reading '0')错误,本质是datefrom/dateto/amount/id这几个绑定用的数组,在子分类渲染前没有对应长度的初始化占位,当下标i访问不存在的数组元素时就会抛出异常。移除下标后所有输入框绑定同一个变量,自然会出现输入内容同步、无法按数组格式存储的问题。

修复方案

方案1(推荐):直接绑定子分类对象属性

该方式无需维护多个独立数组的下标对应关系,稳定性更高。

  1. 调整模板绑定逻辑
<details
  *ngFor="let sub of subCategories; let i = index;"
>
  <summary>{{sub.name}}</summary>
  <ion-row>
      <ion-input type="date" [(ngModel)]="sub.datefrom"></ion-input>
      <ion-input type="date" [(ngModel)]="sub.dateto"></ion-input>
  </ion-row>
  <ion-row>
      <ion-input type="text" [(ngModel)]="sub.amount"></ion-input>
  </ion-row>
  <ion-input type="text" [(ngModel)]="sub.id"></ion-input>
</details> 
  1. 在加载子分类的逻辑中初始化属性
    在optionChanged方法拿到子分类数据后,给每个子分类对象初始化绑定需要的字段:
// 示例代码,可根据实际业务调整
this.subCategories = 接口返回的子分类列表.map(item => ({
  ...item,
  datefrom: '',
  dateto: '',
  amount: ''
}))
  1. 数据提交时直接遍历subCategories数组,即可拿到符合要求的数组格式存储的数据。

方案2:保留独立数组绑定,提前初始化数组

如果需要保留datefrom/dateto/amount/id四个独立数组的写法,在加载子分类时同步初始化数组长度和初始值即可:

// 加载完子分类后执行
const subLength = this.subCategories.length
// 清空旧数据并初始化对应长度的空值
this.datefrom = new Array(subLength).fill('')
this.dateto = new Array(subLength).fill('')
this.amount = new Array(subLength).fill('')
this.id = this.subCategories.map(item => item.id)

其他注意事项

  • 模板代码中ion-select-option上绑定的ionChange事件无效,选中逻辑直接在ion-select的ionChange事件中处理即可。
  • 模板中{{cateogry.name}}存在拼写错误,应为{{category.name}}。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:54:01