Angular中Ag-Grid新增行并提交数据至服务器的技术问询
在Angular的Ag-Grid中实现新增行并提交数据到服务器
需求:点击“Add Row”按钮添加带编辑和删除按钮的空行,编辑MAC地址后,将新增行与原有行数据一同提交至服务器。
当前代码
table.component.html
<button class="btn btn-primary btn-md rounded-pill" (click)="onAddRow()">Add Row</button> <ag-grid-angular #agGrid style="width: 850px;" class="ag-theme-alpine custom-class" [rowData]="rowData" [columnDefs]="columnDefs" [editType]="'fullRow'" [suppressClickEdit]="true" [domLayout]="domLayout" (cellValueChanged)="onCellValueChanged($event)"></ag-grid-angular> <button class="btn btn-primary btn-md float-right rounded-pill" type="submit" (click)="onSubmit()">Apply</button>
table.component.ts
ngOnInit(): void { this.setFormData(); this.getGridData(); this.getMacFilterData(); } getGridData() { this.columnDefs = [ { headerName: 'MAC Address', field: 'DeviceMacAddress', cellStyle: { 'font-color': 'black', 'font-size': '11px' }, resizable: true, suppressSizeToFit: true, width: 400, editable: true, colId: "action", sortable: true, filter: true, valueGetter: params => { return params.data.DeviceMacAddress; }, valueSetter: params => { params.data.DeviceMacAddress = params.newValue; return true; } }, { headerName: 'Actions', cellRendererFramework: RemoveRendererComponent, editable: false, colId: "action", width: 450, cellStyle: { fontSize: '11px' } } ]; this.gridOptions = { columnDefs: this.columnDefs, rowData: null, enableFilter: true, onCellValueChanged: (event) => { console.log("grid-event", event) const gridData = this.getMacFilterData(); } }; } onGridReady(params) { this.gridColumnApi = params.columnApi; this.gridApi = params.api; this.gridApi.sizeColumnsToFit(); } getMacFilterData() { return this.http.get('assets/json/mac.json').subscribe((data:any)=>{ console.log("data", data) this.macStatusValue= data }) } onSubmit() { this.settings.updateEnabledDisabledString(this.macFilterFormGroup.value.macStatus) let body = { "devicekey": this.deviceService.getDeviceKey(), "settings": { "wireless": { "wlanmacfilter": { "status": '', "blockeddevices": [ this.macStatusValue.blockeddevices], "whitelist": [this.macStatusValue.whitelist] } } } } console.log("body", body) this.macFilterService.updateWlanMacSettings(body).subscribe((response: any) => { if (response.statusCode == 200) { alert("Successfully Updated WlanMac Filter Settings") this.getMacFilterData(); } else { alert('Something went wrong, please try again') } }); } onAddRow() { this.agGrid.api.updateRowData({ add: [{}], }); console.log("length", this.rowData.length) } onCellValueChanged(params) { const colId = params.column.getId(); console.log("colId", colId) }
解决方案
1. 修复新增行数据绑定
当前onAddRow未同步更新rowData数组,需确保新增行数据被正确维护:
onAddRow() { const newRow = { DeviceMacAddress: '' }; // 初始化空MAC字段 this.rowData = [...this.rowData, newRow]; // 触发Angular变更检测 this.agGrid.api.updateRowData({ add: [newRow] }); // 同步更新表格 }
2. 统一收集所有行数据用于提交
在onSubmit中直接从Ag-Grid获取当前所有行数据,替换原有静态数据逻辑:
onSubmit() { this.settings.updateEnabledDisabledString(this.macFilterFormGroup.value.macStatus); // 获取所有非空的MAC地址 const validMacs = this.agGrid.api.getRowData() .map(row => row.DeviceMacAddress?.trim()) .filter(mac => mac); let body = { "devicekey": this.deviceService.getDeviceKey(), "settings": { "wireless": { "wlanmacfilter": { "status": this.macFilterFormGroup.value.macStatus, "blockeddevices": validMacs, // 替换为表格中所有有效MAC "whitelist": [] // 根据业务需求调整 } } } }; this.macFilterService.updateWlanMacSettings(body).subscribe((response: any) => { if (response.statusCode == 200) { alert("MAC地址设置已成功更新"); this.getMacFilterData(); // 刷新表格数据 } else { alert('操作失败,请重试'); } }); }
3. 优化表格初始化逻辑
在getMacFilterData中将接口返回数据转换为表格所需的行结构:
getMacFilterData() { this.http.get('assets/json/mac.json').subscribe((data: any) => { this.macStatusValue = data; // 将blockeddevices数组转换为表格行数据 this.rowData = data.blockeddevices.map(mac => ({ DeviceMacAddress: mac })); // 刷新表格 if (this.agGrid.api) { this.agGrid.api.setRowData(this.rowData); } }); }
4. 完善删除行功能(配合自定义组件)
在父组件添加删除方法,供RemoveRendererComponent调用:
// 父组件新增方法 onDeleteRow(row: any) { this.rowData = this.rowData.filter(item => item !== row); this.agGrid.api.updateRowData({ remove: [row] }); }
5. 简化列定义
移除冗余的valueGetter和valueSetter,Ag-Grid会自动绑定field字段:
// 简化MAC地址列配置 { headerName: 'MAC Address', field: 'DeviceMacAddress', cellStyle: { 'color': 'black', 'font-size': '11px' }, // 修正font-color为color resizable: true, width: 400, editable: true, sortable: true, filter: true }
内容的提问来源于stack exchange,提问作者Abi.D
相关产品推荐
相关产品推荐

