Translate

> | > Angular DataTables Server side pagination & Sorting

Angular DataTables Server side pagination & Sorting

Posted on Friday, November 8, 2019 | 10 Comments


Installation : https://l-lin.github.io/angular-datatables/#/getting-started

Add a table to angular view


<table datatable [dtOptions]="dtOptions" style="width: 99.5% !important;" class="table table-responsive-sm table-bordered table-striped table-sm">
                                                <thead>
                                                    <tr>
                                                    <th>Client ID</th>
                                                    <th>Client Name</th>
                                                    <th>Client Phone</th>
                                                    <th>Join Date</th>
                                                    <th>Email</th>
                                                    <th>Is Active</th>
                                                    <th>Operation</th>
                                                    </tr>
                                                </thead>
                                                <tbody *ngIf="modelList && modelList?.length != 0">
                                                    <tr *ngFor="let m of modelList">
                                                    <td>{{ m.ClientID }}</td>
                                                    <td>{{ m.ClientName }}</td>
                                                    <td>{{ m.ClientPhone }}</td>
                                                    <td>{{ m.JoinDate | date : "MMM d, y" }}</td>
                                                    <td>{{ m.Email}}</td>
                                                    <td>
                                                            <div class="btn-group project-list-ad" *ngIf="m.IsActive">
                                                                    <button class="btn btn-white btn-xs">Active</button>
                                                            </div>

                                                            <div class="btn-group project-list-ad-rd" *ngIf="!m.IsActive">
                                                                    <button class="btn btn-white btn-xs">Unactive</button>
                                                            </div>
                                                    </td>
                                                    <td>
                                                        <button class="btn btn-pill btn-dark" type="button" (click)='editbuttonClick(m.ClientID)'>
                                                        <i class="fa fa-file-o fa-sm mt-1"></i>&nbsp;Edit
                                                        </button>
                                                    </td>
                                                    </tr>
                                                </tbody>
                                                <tbody *ngIf="!modelList || modelList?.length == 0">
                                                    <tr>
                                                    <td colspan="3" class="no-data-available">No data!</td>
                                                    </tr>
                                                <tbody>
                                                </table>

Type ScriptCode

dtOptions: DataTables.Settings = {};
public modelList: ClientList[]; // your model for store dataset
 

    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 10,
      serverSide: true,
      processing: true,
      ajax: (dataTablesParameters: anycallback=> {
        that._http
          .post<DataTablesResponse>(
            //'https://angular-datatables-demo-server.herokuapp.com/',
            this.env.apiUrl + 'api/setup/ClientList_SelectAll_Grid',
            dataTablesParameters, {}
          ).subscribe(resp => {
            //console.log(dataTablesParameters);
            that.modelList = resp.data;


            callback({
              recordsTotal: resp.recordsTotal,
              recordsFiltered: resp.recordsFiltered,
              data: []
            });
          });
      },
      columns: [{ data: 'ClientID' }, { data: 'ClientName' }, { data: 'ClientPhone' }, { data: 'JoinDate' }, { data: 'Email' }, { data: 'IsActive' }, { defaultContent: ''orderable: false }]
    };

export class DataTablesResponse {
    data: any[];
    draw: number;
    recordsFiltered: number;
    recordsTotal: number;
    error :string;
  }
 

C# Server Side Code

 public class DataTablesRootObject
    {
        public int draw { getset; }
        public List<Columncolumns { getset; }
        public List<Orderorder { getset; }
        public int start { getset; }
        public int length { getset; }
        public Search search { getset; }
    }

    public class Search
    {
        public string value { getset; }
        public string product_segment { getset; }
        public string branchid { getset; }
        public string username { getset; }
        public string vendorno { getset; }

        public string fromdate { getset; }
        public string todate { getset; }

        public bool regex { getset; }
    }

    public class Column
    {
        public string data { getset; }
        public string name { getset; }
        public bool searchable { getset; }
        public bool orderable { getset; }
        public Search search { getset; }
    }

    public class Order
    {
        public int column { getset; }
        public string dir { getset; }
    }

public class DataTablesResponse
    {
        public object data { getset; }
        public int draw { getset; }
        public int recordsFiltered { getset; }
        public int recordsTotal { getset; }
        public string error { getset; }
    }

public DataTablesResponse ClientList_SelectAll_Grid([FromBodyDataTablesRootObject dataTablesRootObject)
        {
            //[FromBody] DataTablesRootObject dataTablesRootObject
            DataTablesResponse r = new DataTablesResponse();
            try
            {
                string searchText = "";
                if (dataTablesRootObject.search != null)
                {
                    searchText = dataTablesRootObject.search.value;
                }


                #region single sort code
                string sortInformAtion = "";

                if (dataTablesRootObject.order != null && dataTablesRootObject.order.Count > 0)
                {
                    if (dataTablesRootObject.columns != null && dataTablesRootObject.columns.Count > 0)
                    {
                        sortInformAtion = "ORDER BY " + dataTablesRootObject.columns[dataTablesRootObject.order[0].column].data + " " + dataTablesRootObject.order[0].dir;
                    }
                    //dataTablesRootObject.order[0].column
                }
                if (string.IsNullOrEmpty(sortInformAtion))
                {
                    sortInformAtion = "ORDER BY " + dataTablesRootObject.columns[0].data + " asc";
                }
                #endregion

                string error = "";
                List<DataModel.Setup.ClientListoListAll = serviceClientlist.GetsForGrid(dataTablesRootObject.startdataTablesRootObject.lengthsortInformAtionref errorsearchText);

                r.data = oListAll;

                r.draw = dataTablesRootObject.draw;
                r.error = error;
                if (oListAll != null && oListAll.Count > 0)
                {
                    r.recordsTotal = oListAll[0].RecordCount;
                    r.recordsFiltered = oListAll[0].RecordFilter;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + ex.StackTrace);
            }
            return r;

        }


When table is not refresing after data added then add following code


Add trigger in html page

<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" id="user-table"
                   class="table table-responsive-sm table-bordered table-striped table-sm">

Type Script code

implements AfterViewInit
 
declaration code

@ViewChild(DataTableDirective)
  dtElement: DataTableDirective;
dtTrigger: Subject<TempRChallan= new Subject();
 



  ngAfterViewInit(): void {
    this.dtTrigger.next();
  }

  //ngOnDestroy(): void {
  //   Do not forget to unsubscribe the event
  //  this.dtTrigger.unsubscribe();
  //}

  rerender(): void {
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api=> {
      // Destroy the table first
      dtInstance.destroy();
      // Call the dtTrigger to rerender again
      this.dtTrigger.next();
    });
  }

Call rerender method for table data reload.

Comments:10

  1. how to user serverside in angular with type get not post?

    ReplyDelete
    Replies
    1. angular datatables uses post get not allowed because you have to pass search,sort,and pagination data on server.

      Delete
    2. if you don't need server side pagination sorting searching, then you can use get method.

      Delete
  2. when calling render function after adding new data , its only showing last added record. Not showing other records. Can you please help ? How can i fixed to show all records including newly added record.

    --
    Thanks

    ReplyDelete
    Replies
    1. oh sorry for late reply , can you send your code link.

      Delete
  3. Your blog is really informative. Thanks a ton for posting it.
    Sincerely appreciate it.

    When I am using POST instead of the GET, I am getting 405 error. But with GET data comes fine. But I need server side paginations and all.

    Do you have any tutorial for the same with the Spring Boot Rest Endpoint integration?

    Thanks! :)

    ReplyDelete
  4. can you please mention the source code link please

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Data is fetching from server and binding to that.modelList = resp.data; but it is not reflecting table, could you please help

    ReplyDelete

Powered by Blogger.