How add menu button to ag-Grid row? - ag-grid

I'm using ag-Grid Enterprise Vue.
I see in the docs how to enable a "context menu" that is available by right-clicking any individual cell.
I instead would love to have a special column (pinned to the right) that has a button (maybe looking like ⚙ or ...) that opens a menu upon left-click.
How could I go about enabling this? I have found no examples in the docs.
Ag-grid Cell containing menu button is a similar question but has no answer.

From this comment on this ag-grid-enterprise issue, I was able to fork the example, and I think it will work for my situation.
The relevant code is:
var gridOptions = {
columnDefs: columnDefs,
enableRangeSelection: true,
getContextMenuItems: getContextMenuItems,
allowContextMenuWithControlKey: true,
onCellClicked: params => {
console.log(params);
if(params.column.colDef.field === '...'){
params.api.contextMenuFactory.showMenu(params.node, params.column, params.value, params.event)
}
},
onCellContextMenu: params => {
params.api.contextMenuFactory.hideActiveMenu()
}
};
function getContextMenuItems(params) {
console.log('getContextMenuItems', params);
const node = params.node;
console.log('node.id, node.rowIndex, node.data', node.id, node.rowIndex, node.data);
var result = [
{
name: `Alert 'Row ${node.rowIndex + 1}'`,
action: function() {
window.alert(`Row ${node.rowIndex + 1}`);
},
cssClasses: ['redFont', 'bold']
},
'separator',
{
name: 'Checked',
checked: true,
action: function() {
console.log('Checked Selected');
},
icon: '<img src="../images/skills/mac.png"/>'
},
'copy' // built in copy item
];
return result;
}

Related

Algolia autocomplete doesn't go to the selected URL with static sources

ANSWER GetItemURL is only used for keyboard interactions. It is not used for the mouse handling. Mouse handling is done by the rendered HTML (from the template). The simplest approach is to use a a HREF In your template, or an OnClick handler that takes you to another page!
—————————-
I've copied the default autocomplete code for static sources, the completion and filters work, and getItemURL is called correctly, however on click the URL does not change.
I've created a sandbox you can see ithere.
Default code:
const { autocomplete } = window["#algolia/autocomplete-js"];
const autocomplete_id = "#autocomplete-search-box";
function CreateAutoComplete(appid, search_api_key, index_name) {
console.log("CreateAutoComplete Called");
autocomplete({
container: autocomplete_id,
placeholder: "Type T to get completions",
getSources() {
return [
{
sourceId: "links",
getItems({ query }) {
const items = [
{ label: "Twitter", url: "https://twitter.com" },
{ label: "GitHub", url: "https://github.com" }
];
return items.filter(({ label }) =>
label.toLowerCase().includes(query.toLowerCase())
);
},
getItemUrl({ item }) {
console.log("GetItemURL", item);
console.log("returning", item.url);
return item.url;
},
templates: {
item({ item }) {
return item.label;
}
}
}
];
}
});
}
Remember that getItemUrl() is expecting a keyboard interaction (navigate via arrows and click enter) to navigate over to the result URL, not a click.
This is working in your codesandbox, although the redirect is being blocked by Twitter/Github.

How to disable row group expand functionality on one row?

After a lot of searches in SO without any particular solution, I am compelled to ask this question.
What I want is to hide a row group icon on a single group row. Like in the below picture I have a group row that has only one record, which is already shown in the top row. I want to hide that collapse icon on that single record. Only collapse/expand icon shown when group rows are more than one.
For reference see AG-Grid Master-Detail Section, here they specify which rows to expand. Same functionality I needed here.
I'm using the below versions of AG-Grid Angular (v9)
"#ag-grid-community/core": "^25.3.0",
"#ag-grid-enterprise/row-grouping": "^26.0.0",
"#ag-grid-enterprise/server-side-row-model": "^25.3.0",
"ag-grid-angular": "^25.3.0",
"ag-grid-community": "^25.3.0",
Here is my code:
this.rowModelType = 'serverSide';
this.serverSideStoreType = 'partial';
this.cacheBlockSize = 20;
this.gridOptions = {
rowData: this.loanlist,
columnDefs: this.generateColumns(),
getNodeChildDetails: function(rowItem) {
if (rowItem.orderCount > 1) {
return {
expanded: true
}
} else {
return null;
}
}
}
The issue is the getNodeChildDetails is not accessible. Browser console showing me the below warning and my above code is not working.
This is simple to achieve using a cellRendererSelector on the autoGroupColumnDef. You can specify whether to show the default agGroupCellRenderer or simply return another renderer (or, just return null):
this.autoGroupColumnDef = {
cellRendererSelector: (params) => {
if (params.value == 'United States') {
return null;
} else {
return {
component: 'agGroupCellRenderer',
};
}
},
};
In the example below, we are disabling the row group expand functionality on the United States row.
See this implemented in the following plunkr.
The solution isn't that hard - but could be tough, agreed (one day faced with the same case)
So - the answer is custom cell renderer.
It would look a little bit different (separate column for collapse\expande action) - but you would get all control of it.
Custom rendeder component for this action would look like :
template: `
<em
[ngClass]="{'icon-arrow-down':params.node.expanded, 'icon-arrow-right': !params.node.expanded}"
*ngIf="yourFunctionHere()"
(click)="toggleClick()">
</em>`,
export class MasterDetailActionComponent implements ICellRendererAngularComp {
private params: any;
agInit(params: any): void {
this.params = params;
}
public toggleClick(): void {
this.params.node.setExpanded(!this.params.node.expanded);
}
public yourFunctionHere(): boolean {
// so here you are able to access grid api via params.api
// but anyway params.node - would give you everything related to row also
}
refresh(): boolean {
return false;
}
}
in [ngClass] - you are able to handle the visual part (icons) - modify\customize
and don't forget to add this component in the gridOptions:
frameworkComponents: {
'masterDetailActionCellRenderer': MasterDetailActionComponent,
}
and include this column in your columnDef:
columnDefs: [
headerName: "",
width: 75,
field: "expand",
cellRenderer: "masterDetailActionCellRenderer",
filter: false,
resizable: true,
suppressMenu: true,
sortable: false,
suppressMovable: false,
lockVisible: true,
getQuickFilterText: (params) => { return '' }
]

Is it possible to have own custom Context Menu in ag-Grid-community

Can't find the exact answer.
If i decide to opt-in for vanilla JavaScript (non-Angular & Co) ag-Grid-community edition, can i have easy to add my own custom context menu an other custom extensions?
As i seen their docs, context menu is only enterprise level feature.
I seen some treads that there is some caveats, but i personally did not dig deeper.
In general, how easy is to implement self-built features in ag-Grid-community. Or it is better to write own grid?
We have a custom context menu component in our Angular project with ag-grid community, so it's definitely possible.
How it works:
We define all grid columns in templates. If you want a context menu, you put an empty column into the column set and put a special directive on it. The directive accepts a context menu template, which is passed into a custom cellRendererFramework (a menu trigger button, basically). The directive also configures the column to ensure consistent look across grid instances.
This might be not what you've been looking for if you require for menu to open with right mouse click anywhere in a row, but I suppose it shouldn't be that hard to trigger the menu from a different event (check out ag-grid events, there might something suitable).
The snippets below should be straightforward to adapt for your framework of choice. Given you opted into vanilla JS, you'll have to use regular functions to do the same, something like this:
const grid = withContextMenu(new Grid(element, gridOptions), menuOptions).
Here's an example of how we use it:
<ag-grid-angular>
<ag-grid-column headerName='ID' field='id'></ag-grid-column>
<ag-grid-column [contextMenu]='menu'>
<mat-menu #menu='matMenu'>
<ng-template matMenuContent let-item='data'>
<button mat-menu-item (click)='restoreSnapshot(item.id)'>Restore From Snapshot</button>
<a mat-menu-item [routerLink]='[item.id, "remove"]'>Remove</a>
</ng-template>
</mat-menu>
</ag-grid-column>
</ag-grid-angular>
The directive that applies the menu:
const WIDTH = 42;
export const CONTEXT_MENU_COLID = 'context-menu';
#Directive({
selector: '[agGridContextMenu]'
})
export class AgGridContextMenuDirective implements AfterViewInit {
constructor(private gridComponent: AgGridAngular) {}
#Input()
agGridContextMenu!: ElementRef<MatMenu>;
ngAfterViewInit() {
if (!this.agGridContextMenu) return;
setTimeout(() => {
this.gridComponent.api.setColumnDefs([
...this.gridComponent.columnDefs,
{
colId: CONTEXT_MENU_COLID,
cellRendererFramework: CellRendererContextMenuComponent,
width: WIDTH,
maxWidth: WIDTH,
minWidth: WIDTH,
cellStyle: {padding: 0},
pinned: 'right',
resizable: false,
cellRendererParams: {
suppressHide: true,
contextMenu: {
menu: this.agGridContextMenu
}
}
}
]);
});
}
}
The cell renderer component:
#Component({
selector: 'cell-renderer-context-menu',
template: `
<ng-container *ngIf='params.data && params.colDef.cellRendererParams.contextMenu.menu'>
<button
type='button'
mat-icon-button
[matMenuTriggerFor]='params.colDef.cellRendererParams.contextMenu.menu'
[matMenuTriggerData]='{data: params.data}'
>
<mat-icon svgIcon='fas:ellipsis-v'></mat-icon>
</button>
</ng-container>
`,
styleUrls: ['./cell-renderer-context-menu.component.scss']
})
export class CellRendererContextMenuComponent implements ICellRendererAngularComp {
params!: ICellRendererParams;
agInit(params: ICellRendererParams) {
this.params = params;
}
refresh() {
return false;
}
}
A screenshot:
I followed this blogpost, using community edition ag-grid, and it worked! I was surprised because previously I had the experience that cell renderers didn't allow content outside of the cell boundaries to be shown, but somehow popper/tippy is getting around that (I think it adds itself to the top of the DOM with this section of code appendTo: document.body).
https://blog.ag-grid.com/creating-popups-in-ag-grid/
basically, in my javascript CellRenderer:
class MyCellRenderer{
// https://www.ag-grid.com/javascript-data-grid/component-cell-renderer/
init(e){
this.isOpen = false;
this.container = document.createElement("span");
let menubutton = document.createElement("button");
menubutton.innerHTML="&#x1F80B"; //downward arrow
this.tippyInstance = tippy(menubutton);
this.tippyInstance.disable();
this.container.appendChild(menubutton);
menubutton.addEventListener('click', that.togglePopup.bind(this));
}
getGui() {
return this.container;
}
togglePopup() {
this.isOpen = !this.isOpen;
if (this.isOpen) {
this.configureTippyInstance();
this.eMenu = this.createMenuComponent();
this.tippyInstance.setContent(this.eMenu);
} else {
this.tippyInstance.unmount();
}
}
configureTippyInstance() {
this.tippyInstance.enable();
this.tippyInstance.show();
this.tippyInstance.setProps({
trigger: 'manual',
placement: 'bottom-start',
arrow: false,
interactive: true,
appendTo: document.body,
hideOnClick: true,
onShow: (instance) => {
tippy.hideAll({ exclude: instance });
},
onClickOutside: (instance, event) => {
this.isOpen = false;
instance.unmount();
},
});
}
createMenuComponent() {
let menu = document.createElement('div');
menu.classList.add('menu-container');
let options = {};
options['Delete Row'] = this.menuItemClickHandler.bind(this);
options['Popup an Alert!'] = function(){alert("hello!");};
options['Popup an Alert 2!'] = this.menuItemClickHandler.bind(this);
for (const [key, value] of Object.entries(options)) {
let item = document.createElement('div');
item.classList.add('menu-item');
item.setAttribute('data-action', key.toLowerCase());
item.classList.add('hover_changes_color');
item.innerText = `${key}`; // string formatting example
item.addEventListener('click', value);
menu.appendChild(item);
}
return menu;
}
menuItemClickHandler(event) {
this.togglePopup();
const action = event.target.dataset.action;
if (action === 'delete row') {
this.params.api.applyTransaction({ remove: [this.params.data] });
}
if (action === 'popup an alert 2!') {
alert("2");
}
}
}
and in styles.css:
.hover_changes_color:hover {
background-color: dimgrey;
cursor: pointer;
}

how to remove first menu from ag-grid column menu

Is there an option to remove first menu from ag-grid column menu?
I mean the menu with 'pinSubMenu', 'valueAggSubMenu', 'autoSizeThis', etc.
I want to open the context menu and to see first the filter menu and second the columns visibility menu.
I tried to do this, but it still opens empty menu and I need to navigate to my filter menu:
function getMainMenuItems(params) {
var countryMenuItems = [];
var itemsToExclude = [
'separator', 'pinSubMenu', 'valueAggSubMenu', 'autoSizeThis', 'autoSizeAll', 'rowGroup', 'rowUnGroup',
'resetColumns', 'expandAll', 'contractAll','toolPanel'
];
params.defaultItems.forEach(function(item) {
if (itemsToExclude.indexOf(item) < 0) {
countryMenuItems.push(item);
}
});
return countryMenuItems;
}
Looks like you should be able to accomplish what you want to do within the gridOptions:
gridOptions = {
...
suppressMenuMainPanel: true,
...
}
You can also suppress any of the panels of the column menu:
gridOptions = {
...
suppressMenuMainPanel: true,
suppressMenuColumnPanel: true,
suppressMenuFilterPanel: true,
...
}
This is supposing that you are using the Enterprise version, which I assumed you were based on your usage of the getMainMenuItems function
You need to specify menuTabs in the colDef object:
{
headerName: "ID",
field: "id",
menuTabs: ['filterMenuTab','generalMenuTab','columnsMenuTab']
}
See more details here.

Kendo UI DragAndDrop TreeView item to a ListView

I have a requirement to enable drag and drop from a kendo-ui tree view to a templated list view.
I've tried the following:
1.Enabling dragAndDrop on the treeview and configuring the listview as a kendoDropTarget
2.Disabling dragAndDrop on the treeview and instead configuring that control as kendoDraggable to the listview configured as a kendoDropTarget
<div>
<div id="treeview">
</div></div>
<div id="favorites-window" style="height:185px;width:1170px">
<div class="report-reader" style="height:185px;width:1170px;overflow:auto">
<div id="listView"></div>
</div>
</div>
$("#favorites-window").kendoWindow({
width: "1180",
height: "185",
resizable: false,
draggable: false,
actions: ["Custom"],
title: "Favorites"
});
$("#listView").kendoListView({
selectable: "single",
navigatable: false
}).kendoDropTarget({
drop: function (e) {
console.log(e);
var item = getObjects(nucleusTreeJsonData, 'text', e.draggable.hint.text());
$("#listView").data("kendoListView").dataSource.add(item);
}
});
var inlineDefault = new kendo.data.HierarchicalDataSource({
data: [
{ text: "Furniture", items: [
{ text: "Tables & Chairs" },
{ text: "Sofas" },
{ text: "Occasional Furniture" }
] },
{ text: "Decor", items: [
{ text: "Bed Linen" },
{ text: "Curtains & Blinds" },
{ text: "Carpets" }
] }
]
});
$("#treeview").kendoTreeView({
dragAndDrop: true,
dataSource: inlineDefault,
dataTextField: "text"
});
//.kendoDraggable({
// container: $("#tree-pane"),
// hint: function () {
// return $("#treeview").clone();
// },
// dragstart: draggableOnDragStart
//});
$("#treeview").data("kendoTreeView").bind("dragstart", function (e) {
if ($(e.sourceNode).parentsUntil(".k-treeview", ".k-item").length == 0) {
e.preventDefault();
}
});
/*$("#treeview").data("kendoTreeView").bind("drop", function (e) {
e.preventDefault();
var copy = this.dataItem(e.sourceNode).toJSON();
if (e.dropPosition == "over") {
//var item = getObjects(nucleusTreeJsonData, 'text', e.sourceNode.textContent);
$("#listView").data("kendoListView").add(copy);
}
});*/
$('ul.k-group.k-treeview-lines div').children().css('font-weight', 'bold').find('div').css('font-weight', 'normal');
I'm not having much luck with it. Please take a look at my fiddle. Any suggestions would be greatly appreciated
http://jsfiddle.net/OhenewaDotNet/JQBZN/16/
I know this is an old question but I had it, too, so I went ahead and figured it out using this fiddle.
http://jsfiddle.net/JQBZN/74/
This is really really basic and is probably architected awfully but I think it at least demonstrates the key point(s):
$("#treeview").kendoTreeView({
dragAndDrop: true,
dataSource: inlineDefault,
dataTextField: "text",
drag: function (e) {
/* Manually set the status class. */
if (!$("#treeview").data('kendoTreeView').dataItem(e.sourceNode).hasChildren && $.contains($('#favorites-window')[0], e.dropTarget)) {
e.setStatusClass('k-add');
} else {
e.setStatusClass('k-denied');
}
},
drop: function (e) {
if (e.valid) {
/* Do your adding here or do it in a drop function elsewhere if you want the receiver to dictate. */
}
e.preventDefault();
}
});
If the KendoUI tool set isn't doing what you want it to do, you may find it easier to do what you want to do with jQuery UI. They're both implementing the same jQuery core library.
If you go with jQuery UI, it's simply a matter of binding 'draggable' to the element you want to drag, and 'droppable' to your targets. From there, you can wire up handlers to do pretty much anything you want.
I've set up a simple jsFiddle that demonstrates how this would work:
http://jsfiddle.net/e2fZk/23/
The jQuery code is really simple:
$(".draggable").draggable();
$(".container").droppable({
drop: function (event, ui) {
var $target = $(this);
var $source = ui.draggable;
var newUrl = $source.find("input").val();
alert("dropped on " + $target.attr("id") + ", setting URL to " + newUrl);
$target.find("#imageDiv").html("<img id='myImage' />")
.find("#myImage").attr("src", newUrl);
}
});
The API documentation is here:
Draggable
Droppable