Ng2-smart-table - Angular 2 - Columns and same name - javascript

Following are the columns of my table, i got just this part of the code
products: {
title: 'Prodotto',
filter: false,
class: "colonneTabella",
width: "15%",
valuePrepareFunction: (products) => {
var output ="";
var outputs = "";
products.forEach(function(item){
output = item.productDescription
/* item.variantList.forEach(function(d){
outputs= d.description;
})*/
})
return output+outputs;
}
},
products: {
title: 'Variante',
filter: false,
class: "colonneTabella",
width: "20%",
valuePrepareFunction: (products) =>
products.forEach(function(item){
item.variantList;
item.variantList.forEach(function(d){
outputs= d.description;
})
return outputs;
})
}
Hi all! I'm in the above situation. I need to get datas from a json starting from the "products" key. The problem is that ng2 smart table doesn't allow columns with the same name. I tried, then, to rename the second column with "product.variantList" but the code doesn't accept dot inside the name. Is there any solution? thanks

There was similar problem reported when code breaks if dash ("-") is used in the key. Same solution will apply when dot (".") appears in the key.
Refer to - Reading out JSON using JavaScript

Related

Save column header filter in ag-grid in angular

I am working on an existing application in which they have used ag-grid library for angular for most of the grids that they have in their application. Now the ag-grid gives the functionality to filter the grid based on a column value by using the filter option in the column header. I am giving a link to that https://www.ag-grid.com/angular-data-grid/filtering-overview/. I wanted to implement a feature in which we can save the filter keyword that the user is searching for and when he comes back to the same grid the previous filter is already applied. for example https://plnkr.co/edit/?p=preview&preview here we can pick athlete and filter that by going to the column and searching a value so what I want is that if I search 'abc' I should be able to preserve that. is there a way to do that ? I am giving the colDef for the link above
this.columnDefs = [
{ field: 'athlete' },
{
field: 'age',
filter: 'agNumberColumnFilter',
maxWidth: 100,
},
{
field: 'date',
filter: 'agDateColumnFilter',
filterParams: filterParams,
},
{
field: 'total',
filter: false,
},
];
this.defaultColDef = {
flex: 1,
minWidth: 150,
filter: true,
};
}
Any kind of help is appreciated, thanks :)
You can save the filter applied by using the Grid Event onFilterChanged. Inside here you can get the filterModel by calling api.getFilterModel(). In the plunkr below we are showcasing this by saving the filter model to local storage and restoring it by applying it inside the Grid Event onFirstDataRendered
onFilterChanged(params) {
const filterModel = params.api.getFilterModel();
localStorage.setItem('filterModel', JSON.stringify(filterModel));
}
onFirstDataRendered(params) {
const filterModel = JSON.parse(localStorage.getItem('filterModel'));
if (filterModel) {
params.api.setFilterModel(filterModel);
}
}
See this implemented in the following plunkr
You may also find the following documentation pages relevant:
Saving and Restoring Filter Models
Grid Events
To apply existing filters to ag-grid, it can be done using by setting up filterModel on gridApi.
gridApi.getFilterInstance("fieldName").setModel({
"filterType":"equals", //type of filter condition
"type":"text", //Type of column [text/number/date]
"filter":"value" //Value need to be applied as filter.
})
Similarly onFilterChanged event you can capture changes and apply filter dynamically.

Clean input before change

I'm using handsontable 0.35.1 with a float column. Aim is to allow users to copy paste from spreadsheets (and csvs opened in excel). Problem is, that it comes with some junk that i need to get rid of. Some examples of inputs which are not correctly validated are:
1,000.00
USD 100.00
'10000.00 ' //note there are trailing spaces
I would like to find a way i can manipulate input right before it's written. The only way i've found so far is with beforeChange, but the problem is validation. The system changes input, but seems to have validated already. If i blur in and blur out again, it works.
Here's the fiddle. Steps to reproduce: Enter number a123 -- which should be corrected to 123 and validated as a correct number.
I've tried using beforeValidation instead, but it doesn't work as i intend.
You can use beforePaste callback to clean your input
options = {
columns: [
{ type: 'date' },
{ type: 'numeric', numericFormat: {pattern: '0,0.00'} }
],
colHeaders: ["Date", "Float"],
beforePaste: (data, coords) => {
data.forEach((col, colIndex) => {
col.forEach((row, rowIndex) => {
let value = row.trim().replace(/[^0-9\.\-\+]/g, '')
data[colIndex][rowIndex] = value
})
})
return true
},
}
$('#hot-sheet').handsontable(options)
here is fiddle https://jsfiddle.net/xpvt214o/348195/
Note: you can't create new data array, you've to update data array instead of creating new.
I updated the example https://jsfiddle.net/fma4uge8/29/ this works all in 1 function.
function trimFloat(value) {
return value.trim().replace(/[^0-9\.\-\+]/g, '');
}
options = {
columns: [
{ type: 'date' },
{ type: 'numeric', numericFormat: {pattern: '0,0.00'}, trimWhitespace: true }
],
colHeaders: ["Date", "Float"],
beforeChange: function(changes, source){
let that = this;
_.each(changes, function(change){
if (_.isString(change[3])) {
let value = trimFloat(change[3]);
//prevent endless loop
if (value !== change[3]) {
change[3] = trimFloat(change[3]);
that.setDataAtCell(change[0], change[1], change[3]);
}
}
})
}
}
$('#hot-sheet').handsontable(options)

AngularJS - Concatenate fields in ng-grid column not working

I am working on a site employing ajgularjs that will display data returning from a web api call in an ng-grid display. Earlier problems with the data not displaying after the $http.get were remedied through a service call such as:
services.factory('Filing', ['$resource',
function($resource) {
return $resource('/api/bills');
}]);
I have a need on the ng-grid to concatenate the values of three data columns to display in a single ng-grid column, and this is not working.
On Google's angular site I found a similar question to call a function to resolve the concatenation, so in trying this I came up with the following in my controller .js file:
$scope.billData= Filing.query(); // from services.js
$scope.gridData = $scope.billData;
$scope.gridDefs = [
{ field: 'billNumberColumnDisplay()', displayName: 'Bill' },
{ field: 'AuthorLastName', displayName: 'Author'},
{ field: 'Status', displayName: 'Status'},
{ field: 'Committee', displayName: 'Committee'}
];
$scope.gridOptions = {
data: 'gridData',
columnDefs: 'gridDefs',
enableColumnResize: true,
multiSelect: false
};
//function to concatenate the bill number fields
angular.forEach($scope.gridData, function(row) {
row.billNumberColumnDisplay = function() {
return this.BillId.Chamber + this.BillId.Type.trim() + ' ' + this.BillId.Suffix.replace(/^0+(?!\.|$)/, '');
};
});
The second, third, and fourth columns display just fine, so it's not that the data isn't being returned to the grid. If I just display a single column from my return /api call it also displays in the first column.
So, is there anyone out there who can point me in the right direction here? I wouldn't think concatenating fields would pose such a difficult task, but I am obviously doing something wrong.
Thank you in advance for any assistance,
Dan

how to save a SlickGrid column order (js)?

I have two grids in my application.
var columns1 = [
{
name: "Address",
field: "address"
id: "address",
sortable: true
}
]
var columns2 = [
{
{
name: "Rating, in %",
field: "rating"
id: "rating_percent",
resizable: false
}
]
They are absolutely independent from each other. Also, I have some grid events descriptions in another js file.
grid.onColumnsReordered.subscribe(function (e, args) {
_this.updateHeaderRow();
// here
});
When user changes the columns order, then I want to save this order. Should I change (overwrite) the DOM elements, I mean column1 and column2?
So question: how can I save the columns order?
njr101's answer (using store.js) is great, but note: store.js cannot store functions (i.e. for editors, formatters), so once you store.get() the columns, you'll need to add the functions back, using your original stock "columns" array:
if (store.get('gridColumns')) {
grid.setColumns(store.get('gridColumns')); // Restore settings if available
grid.getColumns().forEach(function(ch) { // Re-create editor and formatter functions
var result = $.grep(columns, function(e){ return e.id == ch.id; });
if (result[0]) {
ch.editor = result[0].editor;
ch.formatter = result[0].formatter;
}
});
}
I have done this before and the easiest way I found was to store the columns in local storage. I use the store.js library which makes this pretty simple.
grid.onColumnsReordered.subscribe(function (e, args) {
store.set('gridColumns', grid.getColumns());
});
When you want to restore the columns (e.g. when the user returns to the page) you can just call:
grid.setColumns(store.get('gridColumns'));

Why does this datagrid sort in a weird order?

I have a datagrid where each row has a column where I have defined a formatter to format the display result depending on what it says in the database and create a div with a background color depending on the database.
I have this structure for my datagrid:
structure: [
{
name: "Name",
field: "name",
width: "auto"
},
{
name: "Initials",
field: "initials"
},
{
name: "E-mail",
field: "email",
width: "auto"
},
{
name: "Kerberos",
field: "kerberos",
width: "120px",
formatter: function(kerberos){
var format = "";
if(kerberos == "password expired" || kerberos == "account expired"){
format = '<div class="yellow" title="'+kerberos+'">'+kerberos+'</div>';
}else if(kerberos == "ok"){
format = '<div class="green" title="'+kerberos+'">'+kerberos+'</div>';
}else{
format = '<div class="red" title="Has no kerberos account">not available</div>';
}
return format;
}
},
When I press the column header to sort, it sorts the rows, put not consistent, so I don't know if it sorts correctly (see image below). How do I define the way the datagrid have to sort this column?
I was thinking it was the HTML <div...> part I do in the formatter due to the <> characters, but it still sorts weird if I only output the text (which by my understanding, should be sorted alphabetically). Does anyone know why this happens and how I can fix it?
EDIT:
forgot to add how i get/assign data. I get a lot of data from a xhr.post in JSON format, then i do as follows:
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
handleAs: "json",
content: {
psearch: "dojoXhrBlank"
},
load: function(jsondata){
// Creating a store for the datagrid
var personStore = new Memory({ data: jsondata });
// Create datastore for datagrid
var gridStore = ObjectStore({objectStore: personStore});
...
I found an answer. The problem lies in ObjectStore. This store (for some reason) wont sort properly and after changing the store type to ItemFileReadStore it sortet properly. The other reason for switching store was that ItemFileReadStore also supports the comparatorMap attribute which allows for custom sorting, ObjectStore dose not support this attribute.
solution:
load: function(jsondata){
var store = new ItemFileReadStore({
data: { identifier: "id", items: jsondata }
});
pgrid = new DataGrid({
store: store,
...

Categories