Angular Ag-Grid点击编辑图标获取对应行数据的实现方法
Angular中Ag-Grid点击行编辑按钮获取对应rowData的实现方案
1. 配置ACTION列的colDef
在表格所在的父组件中,给ACTION列指定自定义渲染组件,并通过cellRendererParams传递点击回调:
// 父组件内的列配置 colDefs = [ // 其他业务列配置... { headerName: '操作', cellRendererFramework: ActionButtonComponent, cellRendererParams: { onEditClick: (rowData: any) => this.handleRowEdit(rowData) }, width: 120, sortable: false, filter: false } ];
2. 改造ActionButtonComponent组件
让组件实现Ag-Grid的ICellRendererAngularComp接口,通过接口方法获取当前行的参数,进而拿到rowData:
import { Component } from '@angular/core'; import { ICellRendererAngularComp, ICellRendererParams } from 'ag-grid-angular'; @Component({ selector: 'app-action-button', template: ` <button class="edit-btn" (click)="triggerEdit()"> <svg><!-- 这里替换成你的编辑图标SVG或字体图标 --></svg> </button> `, styles: [` .edit-btn { border: none; background: transparent; cursor: pointer; } `] }) export class ActionButtonComponent implements ICellRendererAngularComp { private cellParams!: ICellRendererParams; // Ag-Grid初始化时传递参数 agInit(params: ICellRendererParams): void { this.cellParams = params; } // 表格刷新时更新参数 refresh(params: ICellRendererParams): boolean { this.cellParams = params; return true; } triggerEdit(): void { // 直接从参数中获取当前行的rowData const currentRowData = this.cellParams.data; // 调用父组件传递的回调,把rowData传回去 if (this.cellParams.onEditClick) { this.cellParams.onEditClick(currentRowData); } } }
3. 父组件处理编辑逻辑
在父组件中实现接收rowData的方法,进行后续编辑操作:
// 父组件内的编辑处理方法 handleRowEdit(rowData: any): void { console.log('当前编辑行数据:', rowData); // 这里可以添加打开编辑弹窗、跳转编辑页面等业务逻辑 }
注意事项
- 确保
ActionButtonComponent已在Angular模块中声明,且父组件所在模块导入了AgGridModule - 如果不需要父组件统一处理逻辑,也可以直接在
ActionButtonComponent的triggerEdit方法中使用currentRowData做操作,但建议保持子组件的通用性,把业务逻辑放在父组件
内容的提问来源于stack exchange,提问作者Mitul Panchal
相关产品推荐
相关产品推荐

