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

Ionic多选选择框实现报错:无法读取未定义对象的'id'属性

解决Ionic多选Select的取值与数组去重问题

我来帮你搞定这个问题!先拆解下你遇到的两个核心问题,再给你具体的修复方案:

问题根源分析

  1. Cannot read property 'id' of undefined报错:
    你在(ionChange)事件里传递了travels.id,但这里的travels是*ngFor循环的临时变量——当用户触发选择事件时,这个循环的上下文已经不存在了,travels变成了undefined,自然读不到id属性。

  2. $event不是布尔值:
    当<ion-select>开启multiple="true"多选模式时,ionChange事件返回的$event是所有选中项的值组成的数组,而不是单个选项的checked状态(那是单选/单个checkbox的逻辑),所以你代码里event.checked会直接报错,因为数组没有这个属性。

修复步骤

1. 修改HTML代码

移除事件里的travels.id参数,只传递筛选类型和$event(也就是选中值的数组):

<ion-select id="filter3" *ngIf="filter_type.travels" (ionChange)="choose_type('travels', $event)" multiple="true">
  <ion-option *ngFor="let travels of filter_type.travels" [value]="travels.id" [selected]="false">{{travels.name}}</ion-option>
</ion-select>

2. 更新TS逻辑

直接利用多选返回的选中值数组来更新你的过滤器,而且这个数组本身就是去重后的结果,不需要额外判断添加/移除:

choose_type(type: string, selectedValues: number[]) {
  // 直接赋值选中的数组,自动保证值唯一
  this.user_filter[type] = [...selectedValues];
  console.log('User filter app', this.user_filter);
}

如果你更倾向于手动维护数组(比如兼容旧逻辑),也可以这么写:

choose_type(type: string, selectedValues: number[]) {
  // 先清空当前类型的过滤器数组
  this.user_filter[type] = [];
  // 遍历选中值添加到数组(天然去重)
  selectedValues.forEach(val => {
    this.user_filter[type].push(val);
  });
  console.log('User filter app', this.user_filter);
}

这样修改后,既解决了报错问题,又能正确获取多选的所有值,还保证了数组内的值唯一~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:12:20