How to Update the params for every pagination button clicks - javascript

Trying to implement pagination, Initially I'm trying to load datatable with few records, once page loaded trying to click pagination buttons like next or any pagination buttons to update the new set of records. I'm able to get the iStart, iEnd records but unable to update the url for every pagination click. Trying to print the console but function is not calling and console.log is not updated with new params. Could you please suggest me how to do the update the params for API. Here is the sample code,
Sample Demo datatatble is not work with pagination, for verification printing the console for the updated querystring.
ngOnInit(): void {
this.dtOptions = {
processing: true,
destroy: true,
columns: [
{ title: '<input type="checkbox" />' },
{ data: 'index' },
{ data: 'firstname' },
{ data: 'lastname' }
],
infoCallback: (oSettings, iStart, iEnd, iMax, iTotal, sPre) => {
pageStartNo = iStart;
pageEndNo = iEnd;
console.log(pageStartNo, pageEndNo);
// this.loadTable();
}
};
}
loadTable(){
let params = new HttpParams()
.set('param1', '123')
.set('param2', '456')
.set('minNumber', pageStartNo)
.set('maxNumber', pageEndNo);
console.log('params >>>>>>>>>>>>>' + params.toString());
this.http
.get<any[]>(
'https://raw.githubusercontent.com/l-lin/angular-datatables/master/demo/src/data/data.json',
{
params
}
)
.subscribe(response => {
this.persons = response.data;
this.dtTrigger.next();
});
}
HTML code:
<button (click)="loadTable()">Load Table</button>
Sample Demo Stackblitz

If I understand your question correctly, you wanted to apply server-side pagination right?
Here is an official documentation for this.
Add ajax method in dtOptions.
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 10,
serverSide: true,
processing: true,
ajax: (dataTablesParameters: any, callback) => {
console.log('Params', dataTablesParameters);
//If you have different key for page number/size change it
dataTablesParameters.minNumber = dataTablesParameters.start + 1;
dataTablesParameters.maxNumber =
dataTablesParameters.start + dataTablesParameters.length; this.http
.post<any[]>(
'YOUR_API_NAME_HERE',
dataTablesParameters,
{}
)
.subscribe(resp => {
this.persons = resp.data;
//Once API fetched data successfully inform datatable by invoking the callback
callback({
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: []
});
});
},
columns: [{ data: 'id' }, { data: 'firstName' }, { data: 'lastName' }]
};
Working Stackbliz Demo

Related

Calling angular-datatable ajax call on other api response

I am using angular-datatable ( http://l-lin.github.io/angular-datatables/#/basic/server-side-angular-way) .
Instead on assigning to this.dtOptions in ngOnInit, I want to do it in the response of another api, but the ajax call is not going through.
My code :-
ngOnInit(){
this.firstCall();
}
firstCall(){
this.api.serviceMethod().subscribe((data : model1) => {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: data.pageLength,
serverSide: true,
processing: true,
ajax: (dataTablesParameters: any, callback) => {
that.http
.post<DataTablesResponse>(
'api.com/api',
dataTablesParameters, data.req_body, {}
).subscribe(resp => {
that.persons = resp.data;
callback({
recordsTotal: resp.recordsTotal,
recordsFiltered: resp.recordsFiltered,
data: []
});
});
},
columns: [{ data: 'id' }, { data: 'firstName' }, { data: 'lastName' }]
};
})
}
When I am putting the dtOptions assignment in ngOnInit, it is getting called, what am I missing here.
Thank you in advance.
You must set a check in super tag (like : tbody or table when you loop in tr tag).
component.html
<table *ngIf="!loading" ...>
...
...
component.ts
loading = true;
... .subscribe(resp => {
that.persons = resp.data;
loading = false;

Unable to append params dynamically to the API using angular datatables

Trying to load datatable with few records initially and once datatable loaded, trying to click pagination buttons, here trying like if we click on pagination button need to reload the API with latest with updated params and load set of records instead of all records at a time. Developed below code for pagination for huge data,
loadTable() {
this.dtOptions = {
processing: true,
destroy: true,
pagingType: 'full_numbers',
pageLength: 10,
columns: [
{ title: '<input type="checkbox" />' },
{ data: 'index' },
{ data: 'firstname' },
{ data: 'lastname' }
],
infoCallback: (oSettings, iStart, iEnd, iMax, iTotal, sPre) => {
pageStartNo = iStart;
pageEndNo = iEnd;
console.log(pageStartNo, pageEndNo);
params = new HttpParams()
.set('param1', '111')
.set('param2', '222')
.set('minNumber', pageStartNo)
.set('maxNumber', pageEndNo);
console.log('params >>>>>>>>>>>>>' + params.toString());
}
};
this.http
.get<any[]>(
'https://angular-datatables-demo-server.herokuapp.com/',
{
params
}
)
.subscribe(response => {
this.persons = response.data;
this.dtTrigger.next();
});
}
Stackblitz

Updating server from Kendo Color picker inside kendo grid

The Problem
So i am currently trying to implement a color picker inside of a Kendo grid, that will hopefully send the chosen color to my Sql Table. Unfortunately, It doesn't seem as though the Update controller is being reached. I am relatively new to Kendo UI, so there might be some incredibly dumb errors shown.
Questions
I guess my main question would be: How can i call the update method when update is clicked on the grid. Essentially, the color picker and the edit command are showing up in beautiful fashion. I just want to know how i can be sure that the method is being called when 'Update' is clicked, seeing as it is not reaching my controller. Feel free to ask if you need to see more code or perhaps a screen shot.
Code
Config.cshtml ( Grid )
#model IEnumerable<STZN.Models.AGCData.ErrorCode>
#{
ViewBag.Title = "Config";
}
#section HeadContent{
<script src="~/Scripts/common.js"></script>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
editable: "inline",
selectable: "row",
dataSource: {
schema: {
model: {
id: "error_code",
fields: {
color: { type: 'string' }
}
}
},
transport: {
read: {
type: "POST",
dataType: "json",
url: "#Url.Action("ErrorCodes")"
},
update: {
type: "POST" ,
dataType: "json",
url: "#Url.Action("UpdateErrorCodes")",
}
}
},
columns: [
{ command : [ "edit" ] },
{
field: "error_code", title: "Error Code",
},
{
field: "error_description", title: "Error Description"
},
{
field: "color",
width: 150,
title: "Color",
template: function (dataItem) {
return "<div style = 'background-color: " + dataItem.color + ";' </div>"
},
editor: function (container, options) {
var input = $("<input/>");
input.attr("color",options.field);
input.appendTo(container);
input.kendoColorPicker({
value: options.model.color,
buttons: false
})
},
}
]
});
});
</script>
}
Update Controller
public JsonResult UpdateErrorCodes(ErrorCode model)
{
using (var db = new AgcDBEntities())
{
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
db.Configuration.ProxyCreationEnabled = false;
var data = db.ErrorCodes.Where(d => d.error_code == model.error_code).Select(x => new
{
error_code = x.error_code,
description = x.error_description,
color = x.color,
});
return new JsonResult()
{
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
};
}
}
I actually managed to fix my issue by adding an additional input attribute to my editor function in the "color" field. It looks like this:
input.attr("data-bind","value:" + options.field);
There are still some present issues (unrelated to the fix/server update) , but as far as updating to the server, It work's as intended.

Cannot read property 'grid' of undefined in modal?

I have a modal that I want to display pre-selected rows in. However, I keep getting a 'cannot read 'grid' of undefined' error. The UI Grids are defined within the modal, and I declare two Grid Apis with two different names. Here is my code:
This launches the modal:
//edit user group
$scope.editSelectedGroup = function(){
//get the selected row
var row = $scope.gridApiInfo.selection.getSelectedRows();
var modalInstance = $modal.open({
animation: true,
templateUrl: 'userGroupModal.html',
controller: 'UserGroupModalController',
resolve: {
modalTitle: function () {
return "Edit User Group"
},
allDepartments: function () {
return $scope.allDepartments;
},
allRegions: function() {
return $scope.allRegions;
},
isEdit: function(){
return true;
},
row: function(){
return row[0];
}
}
});
This is the modal controller:
.controller('UserGroupModalController',function($scope,$modalInstance,$modal,$window,modalTitle,allDepartments,allRegions,isEdit,row,referenceDataService){
$scope.modalTitle = modalTitle;
$scope.isEdit = isEdit;
$scope.allDepartments= allDepartments;
$scope.allRegions = allRegions;
$scope.form= {
value: "",
description: "",
departments: [],
regions: []
};
$scope.departmentsGrid = {
enableRowSelection: true,
multiSelect: true,
enableRowHeaderSelection: false,
onRegisterApi: function(gridApi) {
$scope.deptGridApi= gridApi;
},
columnDefs: [
{name: 'Name', field: 'name'}
],
data: $scope.allDepartments
};
$scope.regionsGrid = {
enableRowSelection: true,
multiSelect: true,
enableRowHeaderSelection: false,
onRegisterApi: function(gridApi) {
$scope.gridApiRegions = gridApi;
},
columnDefs: [
{name: 'Name', field: 'name'}
],
data: $scope.allRegions
};
if ($scope.isEdit){
$scope.form.value = row.value;
$scope.form.description = row.description;
//pushing selected depts
angular.forEach(row.departments, function(department) {
var deptElementPos=angular.findIndexOf($scope.allDepartments, department.id);
$scope.form.departments.push($scope.allDepartments[deptElementPos]);
});
//pushing selected regions
angular.forEach(row.regions, function(region) {
var regionElementPos=angular.findIndexOf($scope.allRegions, region.id);
$scope.form.regions.push($scope.allRegions[regionElementPos]);
});
//setting pre-selected rows
angular.forEach($scope.form.departments, function(department) {
$scope.deptGridApi.grid.rows.map(function (row) {
if (row.entity.id == department.id) {
row.setSelected(true);
$log.log("row selected: " + row.entity.id);
}
});
});
angular.forEach($scope.form.regions, function(region) {
$scope.gridApiRegions.grid.rows.map(function (row) {
if (row.entity.id == region.id) {
row.setSelected(true);
$log.log("row selected region: " + row.entity.id);
}
});
});
$scope.form.id = row.id;
}
$scope.close = function () {
$modalInstance.dismiss();
};
})
When I click the button to launch the modal, no modal shows up - instead I get a console error saying that it 'Cannot read property 'grid' of undefined' at the line with $scope.deptGridApi.grid.rows.map. Anyone have any suggestions for how to fix this? Thanks in advance!
EDIT: Getting selected rows using deptGridApi and gridApiRegions work - I wrote a test function activated by clicking a button in the modal, shown below:
$scope.getDeptandRegions= function(form){
$log.log($scope.gridApiRegions.selection.getSelectedRows());
$log.log($scope.deptGridApi.selection.getSelectedRows())
};
These log the selected rows fine, even though this also uses the grid APIs. Is it this is only fired after I press a button?
Cannot read property 'grid' of undefined' at the line with $scope.deptGridApi.grid.rows.map
means that :
$scope.deptGridApi === undefined
Looking at your code it is because onRegisterApi is either
Never called
Called with "undefined" as paramener
If you can provide a working code snippet I may be able to help you better

delete a record (client only) in JTable using javascript

I'm using JTable and JQuery for an html page, adding the records manually in JTable using jtable addRecord option. I want to delete the added record based on user selection locally i.e., on client side only. Hence, I use the below code, the record contains TeamName & TeamDescription.
$.fn.deleteTeamRow = function() {
var $selectedRows = $('#TeamContainer').jtable('selectedRows');
$selectedRows.each(function () {
var record = $(this).data('record');
var teamname = record.TeamName;
$('#TeamContainer').jtable('deleteRecord', {
key: teamname,
clientOnly: true,
success: (function() {
alert("record deleted");
}),
error: (function() {
alert("record deletion error!");
})
});
});
};
Unable to either get the success or error alert.
Kindly, let me know how to delete a record on client side only.
I was able to resolve the issue the 'key' was missed while defining the columns in the Table.
$('#TeamContainer').jtable({
selecting: true,
columnResizable: false,
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true,
actions: {
},
fields: {
TeamName: {
title: 'Team Name',
**key: true,**
sorting: true
},
TeamDescription: {
title: 'Team Description',
create: false
}
}
});

Categories