如何在Angular中将mat-table checkbox选中项添加到userIDs数组
解决方法
你可以直接从selection.selected选中集合里提取id赋值给userIDs数组即可,具体代码修改如下:
方法1:基于你原有forEach逻辑修改
首先需要先初始化userIDs数组,避免调用push时报undefined错误:
// 声明并初始化数组,id为数字就用number[],为字符串就换成string[] userIDs: number[] = []; sendRegretMail() { // 清空上次的选中数据,避免累加 this.userIDs = []; this.selection.selected.forEach(s => { console.log(s.id); // 把当前选中项的id推入数组 this.userIDs.push(s.id); }); // 后续POST请求直接使用this.userIDs填充对应字段即可 console.log('已收集的userID数组:', this.userIDs); }
方法2:更简洁的map写法
不需要手动遍历,直接通过数组map方法提取所有id生成新数组:
userIDs: number[] = []; sendRegretMail() { // 直接提取所有选中条目的id生成目标数组 this.userIDs = this.selection.selected.map(item => item.id); // POST请求体构造示例,匹配你接口要求的字段名即可 const requestBody = { userIds: this.userIDs, // 其他请求参数... }; // 此处调用你的POST请求接口即可 }
注意事项
- 必须给
userIDs设置初始空数组= [],否则直接调用push方法会抛出Cannot read properties of undefined (reading 'push')错误 - 每次触发方法时建议先清空旧数组或者直接覆盖赋值,避免历史选中数据被累加进当前数组
- 尽量不要用
any[]定义数组,根据你的id实际类型设置number[]或string[],类型更安全
内容的提问来源于stack exchange,提问作者Ashad peal
相关产品推荐
相关产品推荐

