ag-grid setRowData方法插入新的行到表格中。
//rowData行数据
rowData.push({url:'www.itxst.com',name:'IT小书童','type':'IT'});
//添加新的行
gridOptions.api.setRowData(rowData);
//删除第一行数据
gridOptions.rowData.splice(0, 1);
gridOptions.api.setRowData(gridOptions.rowData);
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>ag-grid 新增行例子</title>
<script src="https://www.itxst.com/package/ag-grid/ag-grid-community.js"></script>
<link href="https://www.itxst.com/package/ag-grid/styles/ag-grid.css" rel="stylesheet" />
</head>
<body>
<input type="button" value=" 新增行 " onclick="add()" />
<br /><br />
<div id="myGrid" style="width: 100%;height: 500px;" class="ag-theme-balham"></div>
<script>
//定义表格列
var columnDefs = [
{ headerName: '网站', field: 'url' },
{ headerName: '名称', field: 'name' },
{ headerName: '分类', field: 'type' },
];
//与列对应的数据; 属性名对应上面的field
var rowData = [
{ url: 'www.163.com', name: '网易', 'type': '游戏' },
{url:'www.alibaba.com',name:'阿里巴巴','type':'电商'},
{url:'www.google.com',name:'Google','type':'搜索引擎'}
];
//将列和数据赋给gridOptions
var gridOptions = {
columnDefs: columnDefs,
rowData: rowData,
onGridReady: function () {
//表格创建完成后执行的事件
gridOptions.api.sizeColumnsToFit();//调整表格大小自适应
},
defaultColDef: {
editable: true,//单元表格是否可编辑
enableRowGroup: true,
enablePivot: true,
enableValue: true,
sortable: true, //开启排序
resizable: true,//是否可以调整列大小,就是拖动改变列大小
filter: true //开启刷选
},
pagination: true, //开启分页(前端分页)
paginationAutoPageSize: true, //根据网页高度自动分页(前端分页)
};
//在dom加载完成后 初始化agGrid完成
document.addEventListener("DOMContentLoaded", function () {
var eGridDiv = document.querySelector('#myGrid');
new agGrid.Grid(eGridDiv, gridOptions);
});
function add() {
rowData.push({url:'www.itxst.com',name:'IT小书童','type':'IT'});
//添加新的行
gridOptions.api.setRowData(rowData);
}
</script>
</body>
</html>