Angular表格行复制功能中for循环无法生成多个副本如何解决?
问题根因
- for循环条件写反:原代码判断条件为
i >= result.CopyQuantity,假设你要复制3行,i初始值为1,1 >= 3结果为false,循环一次都不会执行,这是多份复制失败的核心原因。 - 循环内频繁重置数据源逻辑错误:每次循环都执行
splice(0)清空、重新实例化MatTableDataSource,不仅性能极低,还可能因异步检测问题导致行丢失,完全没有必要。 - 条件判断冗余:
result.StockCheck == null || result.StockCheck == false || result.StockCheck == undefined中,== null已经覆盖了undefined的场景,不需要重复判断。
修复代码
修改后逻辑为:先拿到当前数据源的副本,按指定数量生成所有待插入的行,一次性更新数据源,避免循环内反复操作DOM和数据源:
copyWorkItem(index: any, row: IWorkItem, event: any) { const dialogRef = this._dialog.open(CopyDialogComponent, { width: "550px", data: row, }); dialogRef.afterClosed().subscribe((result: IWorkItemSelection) => { // 先判断返回值合法性,避免空值报错 if (!result || !result.CopyQuantity || result.CopyQuantity < 1) return; // 拿到当前数据源的副本,避免直接修改原数据触发不必要的检测 const tempData = [...this.dataSource.data]; // 循环生成指定数量的行 for(let i= 0; i < result.CopyQuantity; i++){ const item: IWorkItem = { Product: row.Product, ProductCategory: row.ProductCategory, Version: row.Version, ProductBalance: row.ProductBalance, DeliveryWarehouse: row.DeliveryWarehouse, }; if (!result.OrderIdCheck) { item.Order = null; } if (!result.StockCheck) { item.ProductCategory = null; item.Product = null; } if (!result.VersionCheck) { item.Version = null; } if (!result.DeliveryWarehouseCheck) { item.DeliveryWarehouse = null; } if (!result.QuantityCheck) { item.Quantity = null; } // 按原逻辑插在列表开头,如果要插在当前点击行的后面,把unshift换成 tempData.splice(index + 1, 0, item) 即可 tempData.unshift(item); } // 一次性更新数据源,不需要重复实例化 this.dataSource.data = tempData; this.EditIndex = 0; }); }
额外优化建议
如果需要复制的行插入到你点击的原行下方,而非列表顶部,只需要把tempData.unshift(item)替换为tempData.splice(index + 1, 0, item)即可。
内容的提问来源于stack exchange,提问作者TreacleMark
相关产品推荐
相关产品推荐

