Infinite Row Model - Row Height - ag-grid

I am using Ag Grid Infinite row model type for few tables in my application and I need to reduce the row height in this.
I am getting the below error while trying to reduce the height by using for Each Nodes in grid API, please advise.
app.exceptions.ts:33
Type Error: Cannot read property 'Children Cache' of undefined
Below is the Data Source method code:
dataSource: IDatasource = {
getRows: (params: IGetRowsParams) => {
this.gridApi.showLoadingOverlay();
this.isError.emit(false);
const urlObj = {getRowsParams: params, pageSize: this.pageSize};
this.getApiUrl.emit(urlObj);
setTimeout(() => {
this.apiService.get(this.apiUrl).subscribe(data => {
params.successCallback(
data.results && data.results[this.resultsString] ? data.results[this.resultsString] : [],
data.results && data.results[this.totalSystemString] ? data.results[this.totalSystemString] : 0
);
let gridHeight = 0;
this.gridApi.forEachNode((node, index) => {
if (node) {
node.setRowHeight(24);
node.setRowTop(gridHeight);
gridHeight += 24;
}
});
this.gridApi.onRowHeightChanged();
this.gridApi.hideOverlay();
}, err => {
this.isError.emit(true);
});
});
}
};

You can use the rowHeight option directly to set the row height. Check that option here: https://www.ag-grid.com/javascript-grid-properties/#renderingStyling

Related

ag-grid continues to show the loading icon when no data returned from the server

I'm facing a strange behavior in Ag-grid (Angular). When I use the serverSide option and when there is no data returned from the server, the grid is showing the loading icon for all the rows mentioned in the cacheBlockSize. I've tried as many options I could to hide these empty loading rows, but nothing has worked out.
I've tried to replicate the same in the official example page. Luckily I could replicate the similar behavior. Refer to this edited version of an official example page, where I'm passing an empty array from the fake server call:
https://plnkr.co/edit/Egw9ToJmNE7Hl6Z6
onGridReady(params) {
this.gridApi = params.api;
this.gridColumnApi = params.columnApi;
this.http
.get('https://www.ag-grid.com/example-assets/olympic-winners.json')
.subscribe((data) => {
let idSequence = 0;
data.forEach((item) => {
item.id = idSequence++;
});
const server = new FakeServer(data);
const datasource = new ServerSideDatasource(server);
params.api.setServerSideDatasource(datasource);
});
}
}
function ServerSideDatasource(server) {
return {
getRows: (params) => {
setTimeout(() => {
const response = server.getResponse(params.request);
if (response.success) {
params.successCallback(response.rows, response.lastRow);
} else {
params.failCallback();
}
}, 2000);
},
};
}
function FakeServer(allData) {
return {
getResponse: (request) => {
console.log(
'asking for rows: ' + request.startRow + ' to ' + request.endRow
);
const rowsThisPage = allData.slice(request.startRow, request.endRow);
const lastRow = allData.length <= request.endRow ? data.length : -1;
return {
success: true,
rows: [],
lastRow: lastRow,
};
},
};
}
The screenshot of the plunker output is given below.
Just figured out that its a problem with lastRow value. If the rows are empty but lastRow is not -1, then its trying to load the data and showing the loading icon for all the rows as per the cacheBlockSize.
Fixed code below:
function FakeServer(allData) {
return {
getResponse: (request) => {
console.log(
'asking for rows: ' + request.startRow + ' to ' + request.endRow
);
let data = []; //allData;
const rowsThisPage = data.slice(request.startRow, request.endRow);
const lastRow = data.length <= request.endRow ? data.length : -1;
return {
success: true,
rows: rowsThisPage,
lastRow: lastRow,
};
},
};
}
Update for AG Grid 28:
function FakeServer(allData) {
return {
getResponse: (params) => {
const request = params.request;
console.log(
'asking for rows: ' + request.startRow + ' to ' + request.endRow
);
let data = []; //allData;
const rowsThisPage = data.slice(request.startRow, request.endRow);
const lastRow = data.length <= request.endRow ? data.length : -1;
params.success({ rowData: rowsThisPage, rowCount: lastRow });
},
};
}

Problem inserting checkbox in select using DataTables

I'm looking for a way to insert a checkbox into a select and fetch each column individually, all using DataTables. I found an excellent example in https://jsfiddle.net/Lxytynm3/2/ but for some reason, when selecting all records, filtering does not display the data as expected. Would anyone have a solution to work properly?
Thanks in advance.
The link application code is as follows:
$(document).ready(function() {
function cbDropdown(column) {
return $('<ul>', {
'class': 'cb-dropdown'
}).appendTo($('<div>', {
'class': 'cb-dropdown-wrap'
}).appendTo(column));
}
$('#example').DataTable({
initComplete: function() {
this.api().columns().every(function() {
var column = this;
var ddmenu = cbDropdown($(column.header()))
// -------------------------------------------------------
.on('change', ':checkbox', function() {
var active;
var vals = $(':checked', ddmenu).map(function(index, element) {
active = true;
return $.fn.dataTable.util.escapeRegex($(element).val());
}).toArray().join('|');
column
.search(vals.length > 0 ? '^(' + vals + ')$' : '', true, false)
.draw();
// -------------------------------------------------------
// Highlight the current item if selected.
if (this.checked) {
$(this).closest('li').addClass('active');
// If 'Select all / none' clicked ON
if ($(this).val() === "1") {
$(ddmenu).find('input[type="checkbox"]').prop('checked', this.checked)
//$(".cb-dropdown li").prop('checked', true);
//$('.cb-dropdown').closest('li').find('input[type="checkbox"]').prop('checked', true);
// $('this input[type="checkbox"]').prop('checked', true); works!
// $( 'input[type="checkbox"]' ).prop('checked', this.checked);
// $(this).find('input[type="checkbox"]').prop('checked', this.checked)
//$('div.cb-dropdown-wrap.active').children().find('input[type="checkbox"]').prop('checked', this.checked)
}
} else // 'Select all / none' clicked OFF
{
$(this).closest('li').removeClass('active');
// test if select none
if ($(this).val() === "1") {
// code to untick all
$(ddmenu).find('input[type="checkbox"]').prop('checked', false)
}
}
// Highlight the current filter if selected.
var active2 = ddmenu.parent().is('.active');
if (active && !active2) {
ddmenu.parent().addClass('active');
// Change Container title to "Filter on" and green
//$(this).parent().find('.cb-dropdown li:nth-child(n+1)').css('color','red');
$('active2 li label:contains("Filter OFF")').text('Yeees');
} else if (!active && active2) {
ddmenu.parent().removeClass('active');
}
});
// -------------------------------------------------------
var mytopcount = '0'; // Counter that ensures only 1 entry per container
// loop to assign all options in container filter
column.data().unique().sort().each(function(d, j) {
// Label
var $label = $('<label>'),
$text = $('<span>', {
text: d
}),
// Checkbox
$cb = $('<input>', {
type: 'checkbox',
value: d
});
$text.appendTo($label);
$cb.appendTo($label);
ddmenu.append($('<li>').append($label));
// -----------------
// Add 'Select all / none' to each dropdown container
if (mytopcount == '0') // Counter that ensures only 1 entry per container
{
$label = $('<label>'), $text = $('<span>', {
text: "Select all / none"
}),
$cb = $('<input>', {
type: 'checkbox',
value: 1
});
$text.prependTo($label).css('margin-bottom', '6px');
$cb.prependTo($label);
ddmenu.prepend($('<li>').prepend($label).css({
'border-bottom': '1px solid grey',
'margin-bottom': '6px'
}));
mytopcount = '1' // This stops this section running again in cotainer
}
});
});
}
});
});
It seems as though the issue was with the select all checkbox. One solution would be to check for "1" within the vals initialisation, this seems to work:
var vals = $(':checked', ddmenu).map(function(index, element) {
if($(element).val() !== "1"){
return $.fn.dataTable.util.escapeRegex($(element).val());
}
}).toArray().join('|');
That should see you with some results upon the top checkbox being checked. Hope that helps.

How to customise the ghost-text (drag item name) with AgGrid

As per title, is there a way to customise the "ghost text" with the (unmanaged) row-dragging implementation in AgGrid via the API?
I found workaround using valueGetter property to change this text.
Example configuration of column:
private dragDropColumn= {
rowDrag: true,
...
valueGetter: (params) => {
return params.data.myVariableFromRow;
}
}
Hope this helps
You can now use colDef.rowDragText to set a callback function to set the dragged text.
https://www.ag-grid.com/javascript-grid-row-dragging/#custom-row-drag-text
onRowDragEnter event,
you could search for the ghost element
and then append your custom class to it.
document.querySelectorAll('.ag-dnd-ghost')[0]
.classlist.add('my-custom-ghost-element');
Dont forget to follow the hierarchy of classes, otherwise you would end up using !important in the custom class :-)
// For updating text
search for the element with className ag-dnd-ghost-label
document.querySelectorAll('.ag-dnd-ghost-label')[0]
.innerHTML = 'your_custom_text';
Ghost element is added only during drag, once drag is ended, its removed from dom by Ag-Grid.
Hope this helps
I've researched this and there is nothing built in to ag-grid. I accomplished this by attaching to the onRowDragMove and onRowDragMove events.
I set a class variable 'isRowDragging' to only do this once while dragging.
I use the Angular Renderer2 class (this.ui) to find and update the Element of the ghost label.
All of this is available with vanilla javascript or other supported ag-grid frameworks.
this.gridOptions.onRowDragMove = (params: RowDragMoveEvent) => {
const overNode = params.overNode;
const movingNode = params.node;
if (!this.isRowDragging) {
this.isRowDragging = true;
if (!movingNode.isSelected()) {
if (params.event && params.event.ctrlKey) {
movingNode.setSelected(true);
}
if (params.event && !params.event.ctrlKey) {
movingNode.setSelected(true, true);
}
}
let labelText: string = '';
const selectedNodes = this.gridOptions.api.getSelectedNodes();
if (selectedNodes.length === 1) {
labelText = selectedNodes[0].data.Name;
}
else {
const guids: string[] = [];
let folderCount: number = 0;
let docCount: number = 0;
selectedNodes.forEach((node: RowNode) => {
guids.push((node.data.FolderGuid || node.data.DocumentGuid).toLowerCase());
if (node.data.FolderGuid !== undefined) {
folderCount++;
}
else {
docCount++;
}
});
if (folderCount === 1) {
labelText = '1 folder';
}
else if (folderCount > 1) {
labelText = folderCount + ' folders';
}
if (docCount === 1) {
labelText += (labelText !== '' ? ', ' : '') + '1 document';
}
else if (docCount > 1) {
labelText += (labelText !== '' ? ', ' : '') + docCount + ' documents';
}
}
console.log(this.ui.find(document.body, '.ag-dnd-ghost').outerHTML);
this.ui.find(document.body, '.ag-dnd-ghost-label').innerHTML = labelText;
}
}
this.gridOptions.onRowDragEnd = (event: RowDragEndEvent) => {
this.isRowDragging = false;
}
I am using ag-grid with react and using cellRendererFramework property of ColDef to use custom react component, my value getter returns object, so when I start dragging I am getting [object object], I added toString method to returning object and did the trick, below is my sample code
const col1 = {
rowDrag: true,
...
valueGetter: (params) => {
const {id, name} = params.data;
return {id, name, toString: () => name}; // so when dragging it will display name property
}
}

Ag-grid hiding rows

Is there any implemented functionality to conditionally hide rows?
I instantiate them like this:
let rows = [
{ name: "Adam", isVisible: true },
{ name: "Bert", isVisible: true },
{ name: "Carl", isVisible: false }
];
for(let row of rows)
row["height"] = row.isVisible ? 25 : 0;
this.rowData = rows;
And then I provide this function to set the row height:
this.gridOptions.getRowHeight = (params) => {
return params.data.height;
}
This is not a perfect solution, especially because if the grid ends with a row of height 0 it shows that row anyway (with the height of 4px or so)
I think the best way would be to filter the data based on the property isVisible of the object.
An implementation could be:
gridOptions.isExternalFilterPresent = () => {return true;}
gridOptions.doesExternalFilterPass = (node) => {
return gridOptions.api.getValue("isVisible", node)
}
if the datamodel data changes then you just need to call gridOptions.api.onFilterChanged()
As a workaround for the 4px issue when setting row height to 0, i suggest you also use
gridOptions.getRowStyle = function(params) {
//some filter
return { 'display': 'none' };
}

How to add Handler on Cell in Google Visualization Table in GWT?

Google Visualization API for GWT provides control over rows only.
How to get control over a particular cell in Visualization Table?
selection.isCell() doesn't give true result in any case.
private SelectHandler createSelectHandler(final PieChart chart) {
return new SelectHandler() {
#Override
public void onSelect(SelectEvent event) {
String message = "";
// May be multiple selections.
JsArray<Selection> selections = chart.getSelections();
for (int i = 0; i < selections.length(); i++) {
// add a new line for each selection
message += i == 0 ? "" : "\n";
Selection selection = selections.get(i);
if (selection.isCell()) {
// isCell() returns true if a cell has been selected.
// getRow() returns the row number of the selected cell.
int row = selection.getRow();
// getColumn() returns the column number of the selected cell.
int column = selection.getColumn();
message += "cell " + row + ":" + column + " selected";
} else if (selection.isRow()) {
// isRow() returns true if an entire row has been selected.
// getRow() returns the row number of the selected row.
int row = selection.getRow();
message += "row " + row + " selected";
} else {
// unreachable
message += "Pie chart selections should be either row selections or cell selections.";
message += " Other visualizations support column selections as well.";
}
}
Window.alert(message);
}
};
}
Google Table has 4 events: ready,select,page,sort.
When you sort or paginate, it stops listening the ready event.
To have the cell click working after pagination or sort you need to add the click listener on all of them.
You can use click instead of mouseover.
On select event I use getSelection to be able to get and set the selected row properties.
var colIndex;
google.visualization.events.addListener(table, 'ready', function () {
$("#table").find("td").each(function() {
$(this).mouseover(function(){
colIndex=$(this).index();
});
});
});
google.visualization.events.addListener(table, 'sort', function () {
$("#table").find("td").each(function() {
$(this).mouseover(function(){
colIndex=$(this).index();
});
});
});
google.visualization.events.addListener(table, 'page', function (event) {
$("#tableGoogle").find("td").each(function() {
$(this).mouseover(function(){
colIndex=$(this).index();
});
});
});
google.visualization.events.addListener(table, 'select', function () {
var selection = table.getSelection();
var item;
if(selection.length!=0){
lastSelection=selection;
}
for (var i = 0; i < lastSelection.length; i++) {
item = lastSelection[i];
}
switch (colIndex){
case 0:
data.setValue(item.row,index,true);
// YOUR CODE FOR COLUMN 0
break;
case 1:
var id=data.getRowProperty(item.row, 'id');
// YOUR CODE FOR COLUMN 1
break;
}
});
The Table Visualization does not pass column information in the selection event, so you cannot identify an individual cell this way. You will need to register a click event handler on the cells of the table and then determine the cell's row and column indices. Here's one way to do it using jQuery:
google.visualization.events.addListener(table, 'ready', function () {
$('#table_div td').click(function () {
var column = $(this).index();
var row = $(this).parent().index() - 1; // subtract 1 for the table header
console.log(row, column);
});
});
You'll have to adapt the event handler to the method used in the GWT Viz API package, but the jQuery code should work.
var rowIndex;
var colIndex;
google.visualization.events.addListener(table, 'ready', function () {
jQuery("#table").on("click", "td:not(.google-visualization-table-th)", function() {
colIndex = jQuery(this).index();
rowIndex = jQuery(this).parent().index() - 1;
alert("row "+rowIndex+" col "+colIndex);
//put rest of function here
});
This gets rowindex based on the row of the html. To get the rowindex based on the data (where the row's index won't change even if you sort the table and it's position changes) use
google.visualization.events.addListener(table, 'select', function() {
var selected=table.getChart().getSelection();
var item=selected[0];
rowIndex=item.row;
});
This will run before the code in the .on("click", ...) function in the ready function.