ag-grid常用代码整理
资料:ag-grid中文教程
- ag-grid常用方法 (其他,常用方法及属性)
//获取选中数据
var rows=gridOptions.api.getSelectedRows();
//全选包含隐藏的行
gridOptions.api.selectAll();
//反选
gridOptions.api.deselectAll();
//根据筛选条件选中行
gridOptions.api.selectAllFiltered();
//根据筛选条件选反行
gridOptions.api.deselectAllFiltered();
//表格宽度自适应
gridOptions.api.sizeColumnsToFit();
//获取第三行对象
var rowNode=gridOptions.api.getRowNode(2);
var x=JSON.stringify(rowNode.data);
//获取当前焦点的单元格
var cell=gridOptions.api.tabToNextCell();
//设置name列的2行获得焦点
gridOptions.api.setFocusedCell(1,'name');
//清除单元格焦点
gridOptions.api.clearFocusedCell();
//设置下一个单元格为当前焦点
gridOptions.api.tabToNextCell();
//设置上一个单元格为当前焦点
gridOptions.api.tabToPreviousCell();
//获取选中的数据
var selRows= this.gridApi.getSelectedRows();
//注意调用updateRowData方法并不会更新vue的data
this.gridApi.updateRowData({remove: selRows});//更新行:删除选中数据(不删vue的data)
//正确的删除方法是这样的
this.rowData = this.rowData.filter(item =>{
return selRows.filter(m=>m.title===item.title).length<=0
} );
//动态设置行高 重新设置为100px
function setHeight()
{
ag.gridOptions.rowHeight=100;
ag.gridOptions.api.resetRowHeights();
}
//更新第一行数据 rowData为行数据
rowData[0].name = 'good';
var params = {
force: true
};
gridOptions.api.refreshCells(params);//更新单元格数据
- ag-grid前端代码
//过长换行
.ag-fresh .ag-header-cell-label .ag-header-cell-text {
display: flex;
align-items: center;
text-align: center;
white-space: normal;
line-height:1;
text-overflow: ellipsis;
height:33px;//设成你的表头高度
}
//selected 背景色
.ag-fresh.ag-grid-module_name .ag-row-focus.ag-row-selected {
background-color: #93CBF6;
}
//行背景黄色(特殊行) 2022-2-17
.row-yellow {
background: yellow !important;
}
//选择有背景色行给选中色 2022-2-17
.ag-row-selected.row-yellow {
background: #93CBF6 !important;
}
<ag-grid-vue class="ag-fresh ag-grid-module_name" :gridOptions="gridOptions"
style="flex: 1;overflow: hidden;margin-left: 8px">
</ag-grid-vue>
- ag-grid列是动态的
/**
* 根据type显示不同标题
* @param type: 1表结构窗口,2数据抽取窗口
*/
public async ShowTable(type:number) {
this.IsCol = type == 1;
this.defaultCols = [
{
headerName: '列标题1',
field: '字段名1',
headerTooltip: '鼠标放上去会显示的文字',
width: 45,
cellStyle: { backgroundColor: "#F6F6F6" },
editable: false,//单元格是否可编辑
},
{
headerName: '列标题2',
field: '字段名2',
width: 145,
cellRenderer: (params) => { //cellEditorFramework 单元格引用组件; valueFormatter与cellRenderer等效?
let t = params.data['字段名2'];
return '<span title="' + t + '">' + t + '</span>';
},
},
];
//来源表 表头
let soruceCols = {
headerName: '来源',
children: [
{
headerName: '数据', field: 'MapName',
width: 75,
editable: true,//单元格是否可编辑
cellEditorFramework: takeSelectCell
},
]
}
//目标表 表头
let targetCols = {
headerName: '目标表',
children: [
{
headerName: '段名', field: 'ColumnName', width: 150,
headerTooltip: '建表',
cellStyle: { borderLeftColor: this.IsCol ? 'red' : 'white' },
cellEditorFramework: takeInputCell
},
]
};
if (this.IsCol) {
this.defaultCols.push(soruceCols, targetCols);
} else {
this.defaultCols.push(targetCols, soruceCols);
}
this.gridOptions.api.setColumnDefs(this.defaultCols);//设置表头
this.tableData = [...];//获得table内容
this.gridOptions.api.setRowData(this.tableData);
}
- ag-grid列固定
public get gridOptions(): GridOptions {
const that = this;
return {
headerHeight: 30,// 表头高度
rowHeight: 30,// 行高
//stopEditingWhenGridLosesFocus:true,
columnDefs: [//列定义
/*{
headerName: '分组',
field: 'PathName',
width: 100,
'pinned': 'left',
rowGroup: true,
rowGroupIndex: 0,
hide: true,
},*/
{ headerName: '',
checkboxSelection: true,
headerCheckboxSelection: true,//出现全选复选框
cellRendererParams: {
suppressCount: true
},
width: 43,
pinned: 'left'
},
{
headerName: '',//序号
width: 25,
cellClass: ['sj_expand_row', 'sj_group_cell'],
cellStyle: (params: any) => {
let rowHeight: number = 0;
let style: any = {
'padding-left': '5px'
}
if (params.node.data['GroupFast']) {
params.api.forEachNodeAfterFilterAndSort(node => {
let dataItem: any = node.data;
console.log('dataItem' + dataItem['OutDeptName']);
if (dataItem['OutDeptName'] == params.node.data['OutDeptName']) {
rowHeight += node.rowHeight;
}
});
style['z-index'] = 1;
style['background-color'] = '#FFF';
style['height'] = rowHeight + "px";
}
return style;
},
cellStyle: { backgroundColor: "#F6F6F6" },
cellRenderer: (params) => {
return (params.node.rowIndex + 1).toString();
},
editable: false,
},
{
headerName: '时间列',
field: that.cyColArray[5], width: 140, editable: true,
valueFormatter(params) {
let t = params.data['时间列'];
return t? t.replace('T', ' '):'' ;
},
suppressKeyboardEvent: function (event) {
return true;
},
cellEditorFramework: takeSelectCell //自定义下拉组件
},
{
headerName: '总费用',
field: '总费用',
width: 200,
cellRenderer: (params) => {
if (params.data) {
let t = true ? '查 看' : '创 建';
let c = v ? 'blue' : 'red';
return ' <a href="javascript:void(0)" style="cursor: pointer;color:' + c + '">' + t + '</a>';
}
return "";
}
},
{
headerName: '项目',
field: 'Xm',
headerClass: 'col-ground',//标题列样式
cellStyle: { backgroundColor: "#F6F6F6" }, //内容行背景色
cellClass:'cell-left',//单元格样式表达式
width: 100,
pinned: 'left'
/*
//样式文件:特殊列标题背景色
.col-ground {
background: #E5FFFF !important;
color: red !important;
}
*/
}
],
//singleClickEdit: true,//单击编辑单元格
//suppressRowClickSelection: true,//点行不选中
showToolPanel: false, // 显示工具栏
enableSorting: true,//允许排序
enableColResize: true,//允许调整列宽
suppressLoadingOverlay: true,// 去掉表格加载数据提示
suppressNoRowsOverlay: true,// 去掉表格无数据提示
suppressDragLeaveHidesColumns: true,//防止拖动的时候隐藏表格列
suppressContextMenu: true,// 阻止表格的右键菜单
defaultColDef: {
cellClass: 'sj_expand_row',
suppressMenu: true,//隐藏表头菜单
},
// treeData: true, // 树形结构
// getDataPath: (params) => { // 添加树形结构属性
// return params.Path; //params.PathName.replace(',ROOT,', '').split(',');
// },
// autoGroupColumnDef: {
// headerName:'人名',//分组列标题
// },
// groupDefaultExpanded: -1,// -1展开所有分组,0折叠(合并)
rowSelection: 'single',//只允许单行选中 multiple
onFilterChanged() {//筛选条件改变回调
},
getRowClass: params => {
let v = params.data['CaseStatus'] + '';
if (v != '0' ) {//
return 'row-yellow';
}
},
// getRowStyle: params => {
// let v = params.data['CaseStatus'] + '';
// if (v != '1' && v != '0') {//添加行内样式(不推荐)
// return { backgroundColor: 'yellow' };
// } else {
// return null;
// }
// },
onCellDoubleClicked: function (event) {//双击单元格触发的事件
let phone = event.data.电话号
},
onRowClicked: function (event) {//行点击事件
},
onCellClicked: function (event) {
},
tabToNextCell() {//禁止键盘导航focus cell
return null;
},
getContextMenuItems: (params: any): any[] => {
if (params.node && !params.node.isSelected()) {
params.node.setSelected(true, true);
}
return [
'separator', {
name: '添加一行',
action: () => {
let emptyRow: any = {.....};
let i = params.node.childIndex;//行索引
that.dataTable.splice(i, 0, emptyRow);//数据源插入空行
that.gridBaby.api.setRowData(that.dataTable);//刷新ag-grid
//let rowNode: RowNode = that.gridBb.api.getRowNode(that.dataTable[that.dataTable.length - 1]);
//if (rowNode) {
//rowNode.setSelected(true);
//that.gridBaby.api.ensureNodeVisible(rowNode);
//}
}
}]
},
onRowSelected: async function (event) {
if (event.node && event.node.isSelected()) {
//必须有此判断,否跟你想的行选中不一样!!! 2023-6-17
}
},
onCellEditingStopped: async (event) => {
event.data.Weight = 123;
let colName = event.colDef.field;//列名称
var abc= event.data.DateHour; //获得指定单元格内容
event.api.updateRowData(event.data); //刷新当前行
},
navigateToNextCell: (params) => {// 支持上下左右键
let previousCell = params.previousCellDef;
const suggestedNextCell = params.nextCellDef;
const KEY_UP = 38;
const KEY_DOWN = 40;
const KEY_LEFT = 37;
const KEY_RIGHT = 39;
switch (params.key) {
case KEY_DOWN:
previousCell = params.previousCellDef;
that.gridOptions.api.forEachNode((node) => {
if (previousCell.rowIndex + 1 === node.rowIndex) {
node.setSelected(true);
}
});
return suggestedNextCell;
case KEY_UP:
previousCell = params.previousCellDef;
that.gridOptions.api.forEachNode((node) => {
if (previousCell.rowIndex - 1 === node.rowIndex) {
node.setSelected(true);
}
});
return suggestedNextCell;
case KEY_LEFT:
case KEY_RIGHT:
return suggestedNextCell;
default:
break;
}
},
};
}
this.gridOptions.columnDefs;//ag-grid所有列集合。可移除或添加列
/**
* 动态加载ag-grid列
*/
setGridCol() {
let defaultCols = [//表头
{
headerName: '操作',//标题
field: '',//字段名
width: 60,
},
];
//this.gridOptions.columnDefs.splice(i, 0, {...});//给表格追加显示列 [必须beforeMounted中]
this.gridOptions.api.setColumnDefs(defaultCols);//给表格追加显示列 【不必beforeMounted中】
this.gridOptions.api.setRowData(data);//填充内容
this.gridOptions.api.setPinnedBottomRowData([{...}]);//底部合计行
}
//给选中行的指定列渲染特定背景颜色 ag-grid 设置单元格以及行的颜色 https://cloud.tencent.com/developer/article/2106132
function ChangRowColor(params:RowClickEvent) {
{
//var column = params.colDef.field;
//params.colDef.cellStyle = { 'backgroundColor': 'red', 'color': '#fff' };
//this.gridOptions.api.refreshCells({
// force: true,
// columns: [column],
// rowNodes: [params.node]
//});
let rIndex = params.rowIndex;
for (let i = 0; i < 50; i++) {
let clr = "#D8E8F5"
if (i == rIndex) {
clr = "#93CBF6"//选中行
}
let row = this.gridOptions.api.getDisplayedRowAtIndex(i) as any;//获得指定行内容
if (row) {
//row['columnController'].displayedLeftColumnTree[index].colDef.cellClass = 'cell-left2'//添加css样式
row['columnController'].allDisplayedColumns[1].colDef.cellStyle = { backgroundColor: clr }
this.gridOptions.api.refreshCells({ force: true, rowNodes: [row] });
}
}
}
/*
let pinnedArr = '姓名,次数,性别,年龄'.split(',')
for (let index = 0; index < pinnedArr.length; index++) {
const element = pinnedArr[index];
//params.source.cellComps[element].column.colDef.cellClass = 'cell-left2'
params.source.cellComps[element].column.colDef.cellStyle = { backgroundColor: "#93CBF6" }
}
this.gridOptions.api.refreshCells({ force: true, rowNodes: [params.node] });
*/
}
- ag-grid常用方法和属性
this.gridCnDiag.api.exportDataAsExcel(null);//导出Excel
let ct = this.gridOptions.api.getModel().getRowCount(); //ag-grid总条数
const cell = gridObj.api.getFocusedCell() as any;//获得选中单元格对象
if (cell) {
const field = cell.column.colDef.field;//字段名称
let rowIndex = cell.rowIndex;
}
//遍历ag-grid
this.gridObj.api.forEachNode((node) => {
if (previousCell.rowIndex - 1 === node.rowIndex) {
node.setSelected(true);
}
});
let rowData = this.gridObj.api.getRowNode(rowIndex).data;//获得指定行内容
let rowselectData = this.gridObj.api.getDisplayedRowAtIndex(deleteRow.rowIndex).data; //获得指定行内容
let rowArr = this.gridObj.api.getSelectedRows(); //获得所有选择行
let nodeArr: RowNode[] = this.gridBaby.api.getSelectedNodes();//获取当前表格的选中node
this.gridObj.api.updateRowData({
add: rowData
});
this.gridObj.api.getDisplayedRowAtIndex(rowIndex).setSelected(true, null);//设置或取消选中行颜色
this.gridObj.api.setFocusedCell(rowIndex, 'name');//下一个单元格设置焦点
this.gridObj.api.clearFocusedCell();//取消选择焦点
that.gridObj.api.ensureNodeVisible(rowNode);//节点可见?
this.gridObj.columnApi.setColumnsVisible(['name','age'], true);//显示/隐藏列 (true显示,false隐藏)
{
this.gridObj.columnApi.getColumn("name").getColDef().headerName = '新名称'//改标题
this.gridObj.columnApi.setColumnWidth("name", 53);//设置列宽度
this.gridObj.api.refreshHeader();
}
this.gridObj.api.ensureColIndexVisible('列英文名');//横滚动条跟随焦点跳转
that.gridObj.api.startEditingCell({
rowIndex: rowIndex,
colKey: '列英文名'
});//下一个单元格设置为可编辑
this.gridObj.api.stopEditing();//结束编辑状态
- 获得ag-grid所有列
/**
* 获得ag-grid所有列
* @param gridObj
* @returns
*/
public static GetGridColumns(gridObj: any) {
let sortColArr = [];//所有列集合
for (let index = 0; index < gridObj.columnDefs.length; index++) {
const element = gridObj.columnDefs[index];
if (element['field'] != 'RowNo' && element['editable'] == true && !element['hide']) {
sortColArr.push(element['field']);
}
}
return sortColArr;
}
- 文本框支持放入焦点选择全部
let inputList = document.querySelectorAll('input');
for (let index = 0; index < inputList.length; index++) {
inputList[index].onfocus = this.selectValue;//onmouseover
}
//全选文本 2021-9-24
selectValue(e) {
e.currentTarget.select();
}
- 动态追加列
<button @click='btnShowTable'>动态追加列</button>
/**
* 动态加载ag-grid列
*/
btnShowTable() {
let that = this as any;
let defaultCols = [//表头
{
headerName: '备注',
field: 'REMARK',
width: 100,
editable: false,//单元格是否可编辑
cellRenderer: (params) => {
let txt = params.data.REMARK;
txt = txt ? txt : '';
return `<div title='${txt}'>${txt}</div>`;
},
},
];
if (this.isShowMore) {
let tempCol = `{
"headerName": "标题",
"field": "字段",
"width": 150,
"editable":true
}`;
defaultCols.push(colObj);
}
this.gridOptions.api.setColumnDefs(defaultCols);
}
public get gridOptions(): GridOptions {
const that = this;
return {
headerHeight: 30,// 表头高度
rowHeight: 30,// 行高
columnDefs: [],//列定义 一定是空对象!!!
showToolPanel: false, // 显示工具栏
singleClickEdit: true,//【单击编辑单元格】
enableSorting: true,//允许排序
suppressRowClickSelection: true,
enableColResize: true,//允许调整列宽
suppressLoadingOverlay: true,// 去掉表格加载数据提示
suppressNoRowsOverlay: true,// 去掉表格无数据提示
suppressDragLeaveHidesColumns: true,//防止拖动的时候隐藏表格列
suppressContextMenu: true,// 阻止表格的右键菜单
defaultColDef: {
suppressMenu: true,//隐藏表头菜单
},
onRowClicked(params) {
params.node.setSelected(!params.node.isSelected());//js选择行
}, onDragStopped: async event => {//列拖动后事件
let cols = event.columnApi.getAllDisplayedColumns();
cols.forEach(element => {
colArr.push(JSON.parse(JSON.stringify(element['colDef'])));
});
console.log(colArr);
}
rowSelection: 'single',//只允许多选中 multiple
onCellClicked: async function (ent) {//单元点击事件
that.selectRow = JSON.parse(JSON.stringify(ent.data));
if (that.selectRow && Object.keys(that.selectRow).includes('QC_TYPE')) {
that.selectRow['QC_TYPE'] = that.selectRow['QC_TYPE'].toString();
}
let itemId = ent.data['ITEM_ID'];
let type = ent.event.srcElement['innerText'];
let isA = ent.event.srcElement['localName'] === 'a';
},
};
}
//按记住的顺序显示列
let arr = colArr;
let currCol = this.gridOptions.columnApi.getColumnState();
let newCol = [];
newCol.push(currCol[0]);
arr.forEach(element => {
let fd = element.field;
if (fd) {
let temp = currCol.filter(item => item.colId === fd);
if (temp && temp.length > 0) {
newCol.push(temp[0])
}
}
});
that.gridOptions.columnApi.setColumnState(newCol);
- 需求:选中一行时执行特定任务。先是用 onRowSelected 很坑,选中行后里面代码会执行两次!!!换成onRowClicked问题解决。
- 怎么指定列排序:
grid1.columnApi.getColumn("SORT_CODE").setSortedAt(true)
- 按参数记住的列顺序重新显示
let currCol = this.gridOptions.columnApi.getColumnState();
let newCol = [];
for(.......){
newCol.push(...)
}
that.gridOptions.columnApi.setColumnState(newCol);
- 表格所有列信息
/**
* 获得表格信息
*/
private GetGridColInfo() {
let that = this;
let arr = that.gridOptions.columnApi.getAllGridColumns()
let colList = [];
for (let index = 0; index < arr.length; index++) {
const element = arr[index]['colDef'] as any;
let hName = element.headerName;
let fd = element.field;
let w = element.width;
colList.push({ i: `${hName}(序号=${index},字段=${fd},列宽=${w})` });
}
console.log(`表格信息2 =`, colList);
}
- 获得ag-grid可视区单元格内容
let arr= document.querySelectorAll('.ag-body');
//获得ag-grid可视区单元格内容
for(let i=0;i<arr.length;i++){
let str =arr[i].innerText;
let arr= arr[i].innerText.split('\n');
if(str && str.length>1)
console.log((i+1)+'--'+arr[i].innerText)
}
- 自定义排序
//生日显示date,但是按age_num排序
{ headerName: '生日', field: 'date', comparator: ()=> {
if (arguments && arguments.length >=5) {
let isAsc = !arguments[4];
if (isAsc) {
let pre = arguments[2].data.AGE_NUM;
let nxt = arguments[3].data.AGE_NUM;
return pre - nxt //升序
} else {
let pre = arguments[3].data.AGE_NUM;
let nxt = arguments[2].data.AGE_NUM;
return nxt - pre //降序
}
}
}
},//自定义排序