- 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選擇行
},
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';
},
};
}
- 需求:我選中一行執行特定任務。先是用onRowSelected 很坑,選中行后里面代碼會執行兩次!!!換成onRowClicked問題解決。
其他:常用方法及屬性