agGrid with Angular, using agRichSelectCellEditor - ag-grid

I have an agGrid populated with Employee records in JSON format from my web service.
[
{
id: 123,
firstName: 'Mike',
lastName: 'Jones',
countryId: 1001,
DOB: '1980-01-01T00:00:00',
. . .
}
I have a second web service returning a list of country codes:
[
{ id: 1000, name: 'France' },
{ id: 1001, name: 'Spain' },
{ id: 1002, name: 'Belguim' }
]
What I'm trying to do is get my agGrid to have a column showing the user's details, including the name of their country, and when they edit this cell, a list of country codes will appear, where they can select one, and it'll update the record with the id of that country.
Basic stuff, no ?
But has anyone managed to get agGrid to successfully use the "agRichSelectCellEditor" to do this successfully ?
{ headerName: 'Country', width: 120, field: 'countryId', editable: true,
cellEditor:'agRichSelectCellEditor',
cellEditorParams: {
// This tells agGrid that when we edit the country cell, we want a popup to be displayed
// showing (just) the names of the countries in our reference data
values: listOfCountries.map(s => s.name)
},
// The "cellRenderer" tells agGrid to display the country name in each row, rather than the
// numeric countryId value
cellRenderer: (params) => listOfCountries.find(refData => refData.id == params.data.countryId)?.name,
valueSetter: function(params) {
// When we select a value from our drop down list, this function will make sure
// that our row's record receives the "id" (not the text value) of the chosen selection.
params.data.countryId = listOfCountries.find(refData => refData.name == params.newValue)?.id;
return true;
}
},
My code seems to be almost correct.. it manages to:
display the country name in each row of the agGrid
display a popup, listing the country names, from our "list of countries" array
when I select an item in the popup, it successfully updates the countryId field with the (numeric) id value of my chosen country
The only problem is that at the top of the popup, it shows the countryId value, rather than the user's current country name.
Has anyone managed to get this to work ?
The only workaround I could come up with was to override the CSS on this popup and hide that top element:
.ag-rich-select-value
{
display: none !important;
}
It works... but you no longer get to see what your previously selected value was.
(I really wish the agGrid website had some decent, real-life, working Angular examples... or at least let developers post comments on there, to help each other out.)

The solution was to use a valueGetter, rather than a cellRenderer:
{
headerName: 'Country', width: 120, field: 'countryId', editable: true,
cellEditor:'agRichSelectCellEditor',
cellEditorParams: {
// This tells agGrid that when we edit the country cell, we want a popup to be displayed
// showing (just) the names of the countries in our reference data
values: listOfCountries.map(s => s.name)
},
valueSetter: function(params) {
// When we select a value from our drop down list, this function will make sure
// that our row's record receives the "id" (not the text value) of the chosen selection.
params.data.countryId = listOfCountries.find(refData => refData.name == params.newValue)?.id;
return true;
},
valueGetter: function(params) {
// We don't want to display the raw "countryId" value.. we actually want
// the "Country Name" string for that id.
return listOfCountries.find(refData => refData.id == params.data.countryId)?.name;
}
},
I hope this is useful...

I was able to get my similar situation (id:name pairs in a list, but not using Angular though) working without the problem you mentioned above, and without a valueGetter/valueSetter and only a renderer. The benefit is that you don't need to double click the cell to see the list, the cell appears as a selection box always, and you avoid a bug should the user double click the cell when the list is displayed.
The renderer is a lot clunkier than I was wanting (one line like yours) and it didn't seem that aggrid had built in support for this pretty basic function (and I already have spent enough time on this).
Anyway, this is what I had, which at least works, but keen to see further improvements on it. (You will need to at least change 2 lines for the option related code since my defaultValue object is specific to me).
The column definition:
{field: 'defaultValueID', headerName: "Default Value", cellEditor:'agRichSelectCellEditor', cellRenderer: defaultValueRenderer}
And the renderer code:
function defaultValueRenderer(params) {
var input = document.createElement("select");
// allow it to be cleared
var option = document.createElement("option");
option.innerHTML = '[None]';
option.value = null;
input.appendChild(option);
for (var i=0; i < defaultValueList.length; i++) {
var option = document.createElement("option");
option.innerHTML = defaultValueList[i].name;
option.value = defaultValueList[i].gltID;
input.appendChild(option);
}
input.value = params.value;
input.onchange = function() {
params.setValue(this.value);
params.data.defaultValueID = this.value;
}
input.style="width: 100%; height: 100%"; // default looks too small
return input;
}

Here Is Example Of agRichSelectCellEditor...
{
headerName: 'Dropdown', field: 'dropdown',
cellEditor: 'agRichSelectCellEditor',
width: 140,
editable: true,
cellEditorParams: (params) => {
values: Get All Dropdown List Like ["Hello","Hiii","How Are You?"]
},
valueSetter: (params) => {
if (params.newValue) {
params.data.dropdown= params.newValue;
return true;
}
return false;
}
}

Much simpler solution: use cellEditorParams formatValue, along with valueFormatter
{
field: 'foo',
cellEditor: 'agRichSelectCellEditor',
cellEditorParams: {
values: [1,2,3, 4, other ids... ],
formatValue: (id: number): string => this.getLabelFromId(value)
},
valueFormatter: (params: ValueFormatterParams): string => this.getLabelFromId(params.value as number)
}

Related

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 '' }
]

ag-grid: call function every time filter is clicked

How to call a function every time the filter icon is clicked in ag-grid. Below is my code. My aim is to reset the filter values of Name column every time filter icon is clicked. I have to use agSetColumnFilter. I tried filterParams but it is not called every time but only ones Can anyone please guide me here?
constructor(private http: HttpClient) {
this.columnDefs = [
{
headerName: "Name",
field: "name",
width: 150,
filter: "agSetColumnFilter",
menuTabs: ['filterMenuTab']
}
];
}
onGridReady(params) {
this.rowData = [
{
name: "A",
flag: true
},
{
name: "B",
flag: false
}
];
}
You can use the postProcessPopup callback (see documentation here). This callback is called every time you click on the filter icon.
Add your callback into your html:
[postProcessPopup]="postProcessPopup"
Then create your postProcessPopup function:
this.postProcessPopup = function(params) {
if (params.column.colDef.field === 'name')
{
var athleteFilter = this.gridApi.getFilterInstance('name');
athleteFilter.selectEverything();
this.gridApi.onFilterChanged();
}
}.bind(this);
If the click filter icon is for the field name, then selecting everything for that filter, then call the onFilterChanged function on the gridApi to make sure it updates.
You can see a working Plunker here (try filtering the "Athelete" field).
More documentation on the filter api can be found here.

ag-grid's agSelectCellEditor doesn't render the cell correctly

I am using agSelectCellEditor to imlement a dropdown menu in a particular column cells.
This is the column definition:
{
headerName: "Rattachement",
field: "rattachement",
editable: true,
headerTooltip:
"Choisissez l'entité de rattachement parmi les choix présents dans la liste déroulante",
cellEditor: "agSelectCellEditor",
cellEditorParams: {
values: [
"",
"Audit",
"RA",
"Consulting",
"FA",
"Tax&Legal",
"ICS",
"Taj"
]
}
}
This is how ag-grid renders it:
I have to doubl-click on it in order for the dropdown list to show-up this way:
And then I can select any of the available options.
As you notice, this is really poor rendering and may cause the user to be confused and unable to use the tool that I am building.
So my question is:
Is there any way to make ag-grid show the dropdown menu from the beginnig without having to double-click on the cell so that the user actually knows what to do?
Thanks!
PS: I don't want to use a custom cell renderer, because the options in the cell depend on other variables and the whole thing may get messy if I choose to implement the dropdown list using a customcellRenderer (which I did with other columns where it doesn't cause me any of the mentioned trouble)
This is the same issue which i encountered :).
By default AgGrid doesnt show dropdown columns. If you wish to show it as a dropdown you will have to use cellRenderer just to show the image to notify user that this is dropdown column.
Double click edit can be changed to singleclick or no click edit that option is avaiable.
Set columndef option singleClickEdit : true,
var columnDefs = [
{field: 'name', width: 100},
{
field: 'gender',
width: 90,
cellRenderer: 'genderCellRenderer',
cellEditor: 'agRichSelectCellEditor',
singleClickEdit : true,
cellEditorParams: {
values: ['Male', 'Female'],
}
},]
var gridOptions = {
components: {
'genderCellRenderer': GenderCellRenderer
},
columnDefs: columnDefs,
}
function GenderCellRenderer() {
}
GenderCellRenderer.prototype.init = function (params) {
this.eGui = document.createElement('span');
this.eGui.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 18 18"><path d="M5 8l4 4 4-4z"/></svg>' + params.value;
};
GenderCellRenderer.prototype.getGui = function () {
return this.eGui;
};
DEMO
Hope this helps.

Ag-Grid: Number Formatting eg:123456.78 to 123,457

I have huge sets of numeric data.
this needs to be rendered as comma separated value.
For Ex.
123456.78 to be rendered as 123,457 using Ag-Grid.
Kindly help me on achieving this.
As per the cell rendering flow documentation (here), you can use the colDef.valueFormatter, like this:
var columnDefs = [
{headerName: "Number", field: "number"},
{headerName: "Formatted", field: "number", valueFormatter: currencyFormatter}
];
function currencyFormatter(params) {
return '£' + formatNumber(params.value);
}
function formatNumber(number) {
// this puts commas into the number eg 1000 goes to 1,000,
// i pulled this from stack overflow, i have no idea how it works
return Math.floor(number).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}
You could also use a cellRenderer as other posts describe, but that's typically for more complex rendering, whereas the valueFormatter is specifically for this case. From the ag-grid documentation:
valueFormatter's are for text formatting.
cellRenderer's are for when you want to include HTML markup and
potentially functionality to the cell. So for example, if you want to
put punctuation into a value, use a valueFormatter, if you want to put
buttons or HTML links use a cellRenderer. It is possible to use a
combination of both, in which case the result of the valueFormatter
will be passed to the cellRenderer.
{
headerName: 'Salary', field: 'sal'
cellRenderer: this.CurrencyCellRenderer
}
private CurrencyCellRenderer(params:any) {
var usdFormate = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 4
});
return usdFormate.format(params.value);
}
Like these we can mention in Angular2 Typescript code.
You can do this by writing a "customcellRenderer", when you create a column definition provide a function to "cellRenderer " attribute and in renderer use number filter, something like this
var colDef = {
name: 'Col Name',
field' 'Col Field',
cellRenderer: function(params) {
var eCell = document.createElement('span');
var number;
if (!param.value || !isFinite(param.value)) {
number = '';
} else {
number = $filter('number')(param.value, 0);
}
eCell.innerHTML = number;
return eCell;
}
}

Extjs grid with multiselect feature to retrieve value of selected lists

Let's say I have a grid with multiselect option on, when user selects 4 lists and wants to get the values ( alerted on screen) how would I do that? And how would I disable buttons untill at least one list is selected?
All questions you've asked are answered many times already. Also there are good ExtJS examples on sencha.com. For example list view grid shows multiple select and editable grid with writable store shows button enable on click. But THE MOST important is documentation! Let me explain functionality on following code. Most of it is from list view example.
This grid gets JSON from list.php which has following structure
{"authors":[{"surname":"Autho1"},{"surname":"Autho2"}]}
And the grid:
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.panel.*'
]);
Ext.onReady(function(){
// Here i've definned simple model with just one field
Ext.define('ImageModel', {
extend: 'Ext.data.Model',
fields: ['surname']
});
var store = Ext.create('Ext.data.JsonStore', {
model: 'ImageModel',
proxy: {
type: 'ajax',
url: 'list.php',
reader: {
type: 'json',
root: 'authors'
}
}
});
store.load();
var listView = Ext.create('Ext.grid.Panel', {
id: 'myPanel', // Notice unique ID of panel
width:425,
height:250,
collapsible:true,
renderTo: Ext.getBody(),
store: store,
multiSelect: true,
viewConfig: {
emptyText: 'No authors to display'
},
columns: [{
text: 'File',
flex: 50,
// dataIndex means which field from model to load in column
dataIndex: 'surname'
}],
dockedItems: [{
xtype: 'toolbar',
items: [{
// This button will log to console authors surname who are selected
// (show via firebug or in chrome js console for example)
text: 'Show selected',
handler: function() {
// Notice that i'm using getCmp(unique Id of my panel)
// to get panel regerence. I could also use
// this.up('toolbar').up('myPanel')
// see documentation for up() meaning
var selection = Ext.getCmp('myPanel').getSelectionModel().getSelection();
for (var i=0; i < selection.length; i++) {
console.log(selection[i].data.surname);
}
}
},{
text: 'Disabled btn',
id: 'myHiddenBtn', // Notice unique ID of my button
disabled: true // disabled by default
}]
}]
});
// Here i'm waiting for event which is fired
// by grid panel automatically when you click on
// any item of grid panel. Then I lookup
// my button via unique ID and set 'disabled' property to false
listView.on('itemclick', function(view, nodes){
Ext.getCmp('myHiddenBtn').setDisabled(false);
});
});
I didn't knew how to do this from top of my head, but I used documentation and the result works ;-). See Grid panel docs for more information.