Click here to Skip to main content
15,904,287 members
Articles / Web Development / HTML

Angular2 Grid Component - Auto Generated

Rate me:
Please Sign up or sign in to vote.
4.87/5 (11 votes)
9 Aug 2016CPOL3 min read 31.1K   791   13   3
Angular2 grid component

Introduction

As I started working on my first Angular2 project, coming from a .NET web development background, I instantly started missing the .NET controls, which used to provide me with a lot of awesome fast and quick components, that you can use and save a lot of time.

The first component that I really missed was the GridView which I used whenever I simply needed to display some data.... so I decided to create my own GridView using Angular2.

I want this component to do the following:

  • Fast and simple data display, no HTML writing at all
  • Provide paging and row deleting without no extra hassle
  • Can be reused, so it has to be customizable according to the different situation

Needed configuration:

  • Excel like column sorting on client side, with the option to switch it on/off
  • Control which columns you want to sort
  • Control allow row delete on/off
  • Pagination ability to add client side / server side searching

Image 1

Background

Beginner level in Angular2, JavaScript and ES6. So if you can create a basic simple Angular2 application and know how to use a component, you are good to go.

Using the Code

Image 2

In order to use this component, you simply need to include inside your application, the component is using a sorting pipe and the data is passed to the component from the main component.

Parts of the code are as follows:

  • AutoGrid.ts
  • AutoGrid.html (optional - HTML can be inside template attribute instead)
  • AutoGridPipe.ts
  • MainComponent.ts (where the component is used and how to call it)

Component Code (AutoGrid.ts)

Needed Packages
JavaScript
import {Component,Input} from '@angular/core';
//Needed for triggering events
import {Subject}    from 'rxjs/Subject';
import {Observable}     from 'rxjs/Observable';
//Needed for sorting
import {AutoGridPipe} from './AutoGridPipe';
Component Block
JavaScript
@Component({
  selector : 'AutoGrid',//tag name in when calling the component
  templateUrl : 'AutoGrid.html',//path of the HTML can be replaced with template:...
  pipes : [AutoGridPipe]//link the Pipe
})
Class

Using @Input() variables, we can configure the behaviour of the component:

  • AllowSorting: Main sorting control, switch on/off sorting option at columns
  • AllowDelete: Hide/display a delete button
  • Columns: Set which columns to display, and which of them are sortable or not

Using Subject variable to trigger events in the main component:

  • RowDeleted$: Once triggered, will hold the whole deleted row
  • PageIndexChanged$: Once triggered, will hold the new page index (starting from 0)
JavaScript
export class AutoGrid
{
  SortBy : string = "";//This param is used to determine which column to use for sorting
  Direction: number = 1;//1 is ascending -1 is descending

  Pages : any = [];//Dummy array to load the pagination
  Data : any = [];//Main data container
  Width:string;
  @Input() AllowDelete : boolean= true;//Can a row be deleted
  @Input() Columns : any = [];//Name of the columns to display / order
  @Input() AllowSorting : boolean= true;//Allow client side sorting
  @Input() TotalRows : number = 0;//Total number of rows for paging
  @Input() PageSize : number = 0;
  @Input() PageIndex : number = 0;//To control the start page index

  public RowDeleted$ = new Subject<any>();//Subscribe to this to handle delete event
  public PageIndexChanged$ = new Subject<any>();//Subscribe to this to handle "page index change" event

  public LoadData(_data : any)
  {//Main method to load the data
    this.Data = _data;
  }
  OnDeleteRow(Row2Delete:any)
  {//private method to raise RowDeleted
    this.RowDeleted$.next(Row2Delete);
    //client side delete for data can be done here
  }
  OnPageIndexChange(index:number)
  {//private method to raise RowDeleted
    console.log(index);
    this.PageIndex = index-1;
    this.Data = [];
    this.PageIndexChanged$.next(index-1);
  }
  ngOnInit(){
    //used for pagination style
    let totalPages : any = (this.TotalRows / this.PageSize);
    this.Width = ((totalPages * 38) + totalPages * 2) + "px";
  }
  ngAfterViewInit() {
    //fill the dummy array
    for(let i=0;i<this.TotalRows / this.PageSize;i++)
    this.Pages.push(i+1);
  }
   Sort(key:string,dir:number){
     //Change the sorting criteria
       this.SortBy = key;
       this.Direction = dir;
   }
}

Component HTML (AutoGrid.html)

As mentioned before, the whole HTML part can be moved into AutoGrid.ts inside template parameter.

HTML
<!--Just to give the pagination a better look-->
<style>
.nav{border:solid 1px #777;float:left;padding:8px; margin:1px;  width:38px; text-align: center;}
</style>
<!--End of style-->
<table class="table">
  <tr>
    <!--Generate column names ... loop on columns array-->
    <th *ngFor="let col of Columns">{{col.colName}}
      <!--If sorting is allow and its enabled for this column, we switch between ascending/descending-->
    <a [hidden]="Direction==-1 || !AllowSorting || 
    !col.sortable" (click)="Sort(col.colName,-1)">?</a>
    <a [hidden]="Direction==1 || !AllowSorting || 
    !col.sortable" (click)="Sort(col.colName,1)">?</a>
    </th>
    <!--For the delete link-->
    <th [hidden]="!AllowDelete"></th>
  </tr>
  <!--Loop on the data-->
  <tr *ngFor="let c of Data | AutoGridPipe : [SortBy,Direction]; let i = index;">
    <td *ngFor="let col of Columns">{{c[col.colName]}}</td>
      <!--show delete if enabled, and pass the whole row to OnDeleteRow-->
      <td [hidden]="!AllowDelete"><a (click)="OnDeleteRow(c)">X</a></td>
  </tr>
</table>
<!--Pagination-->
<table class="table">
  <tr>
    <td>
      <div style="margin:0px auto;" [style.width]="Width">
      <!--Width is calculated based on number of pages, to make it center-->
      <div *ngFor="let pageIndex of Pages;let i = index;" class="nav">
        <!--If this is the current page, page number displayed as a text only-->
        <span [hidden]="PageIndex!=i">{{pageIndex}}</span>
        <!--Page number displayed as a link, 
            which call OnPageIndexChange and pass the new PageIndex + 1 -->
        <a [hidden]="PageIndex==i" 
        (click)="OnPageIndexChange(pageIndex)">{{pageIndex}}</a>
      </div></div>
    </td>
  </tr>
</table>

Sorting Pipe

As Angular2 doesn't provide you with default sorting and filtering, we need to implement a pipe in order to do the sorting, the pipe is created in a separate file.

The sorting is done based on 2 variables, which column to sort with and which direction (represented by 1 / -1).
In order to make this component reusable regardless of the data, we have to access the property as an array, e.g., a["param"] or b["param"].

AutoGridPipe.ts

JavaScript
import {Pipe ,PipeTransform} from '@angular/core';
@Pipe({
  name:'AutoGridPipe',//name will be used in the page
  pure: false
})
export class AutoGridPipe implements PipeTransform
{
  //Sort,Dir ... will be passed through the component
  transform(array: any[],[SortBy,Dir] : string)
  {
    array.sort((a: any, b: any) =>
    {
      if (a[SortBy] > b[SortBy]) {
        return 1 * Dir;//we switch ascending and descending by multiply x -1
      }
      if (a[SortBy] < b[SortBy]) {
        return -1 * Dir;//we switch ascending and descending by multiply x -1
      }
      return 0;
    });
    return array;
  }
} 

Main Component

Using the grid component is pretty simple, we start by simply importing it, assuming that all the files are in the same folder, and then use the selector that we chose earlier in our definition <AutoGrid>.

JavaScript
import {AutoGrid} from './AutoGrid';
//ViewChild Needed whenever you want to access a child component property or method
import {Component,ViewChild} from '@angular/core';
JavaScript
@Component({
  selector:'MainComponent',
  template: `
           <AutoGrid
           [Columns]="Columns2Display"
           [AllowDelete]="true" [TotalRows]="100" [PageSize]="20">
           </AutoGrid>`,
  directives: [AutoGrid]
})
JavaScript
export class MainComponent
{
//Dummy data to be loaded
Items2Load : any = [
                 {Key:'1', paramName:'Dummy',
                 readType:'Post' ,regEx:'d+',mapValue:'31',priority:2},
                 {Key:'2', paramName:'Something',
                 readType:'GET' ,regEx:'&^',mapValue:'44',priority:1},
                 {Key:'3', paramName:'Hello',
                 readType:'JSON' ,regEx:'w+',mapValue:'333',priority:4},
                 {Key:'4', paramName:'Goo',
                 readType:'XML' ,regEx:'OSOSOS',mapValue:'555',priority:6}];

//Columns to display, enable / disable sort
//Basically any column base configuration needed, can be added here
//Such as Display name, column Icon ....
Columns2Display : any =[
                {colName: "Key", sortable:true},
                {colName: "paramName", sortable:true},
                {colName: "readType", sortable:false},
                {colName: "regEx", sortable:true},
                {colName: "mapValue", sortable:true},
                {colName: "priority", sortable:true}];

//Through this we can access the child component through _AutoGrid
@ViewChild(AutoGrid)  private _AutoGrid:AutoGrid;

//Load the data into the child component
//Cannot be done inside constructor as you don't have access to ViewChild in constructor

ngOnInit(){

      //Pass the data to child component, through LoadData method
      this._AutoGrid.LoadData(this.Items2Load);

      //Can be loaded using ajax call or service
      //this._dummy service.LoadItems((res:any)=>{
      //  this._AutoGrid.LoadData(res);
      //});
  }

//Handle the events (Delete / PageIndexChanged)
ngAfterViewInit() {
      this._AutoGrid.RowDeleted$.subscribe(c => console.log("I saw you, deleted " + c.Key));
      this._AutoGrid.PageIndexChanged$.subscribe(c=> console.log("New page id " + c));
  }
} 

Points of Interest

This control can be modified and customized to add more features (editing, client side filtering, server side filtering, server side sorting and more), in case we want to implement a new server side event (a subject variable needs to be used and can be handled by subscribing to it in the main component). Otherwise, your code will be inside the grid component.

As I consider myself a beginner in Angular2, my code or the methods that I am using are far from optimum and not to be considered as a best practice so any comments are welcome here.

History

  • 9th August, 2016: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
United Arab Emirates United Arab Emirates
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionGrid Component Code made more efficient through api service call, pagination and server side sorting Pin
Tejas kapadia20-Mar-17 3:37
Tejas kapadia20-Mar-17 3:37 
I have made major modifications and included below mentioned things
1) Fetched data through WEB API
2) Client side sorting removed. Called same API service to perform sorting on all the records of database. Also, Sorting image issue solved.
3) Pagination - Page numbers display restricted to 5 Page in case when total pages are more than 5. Added Next, Previous, First and last buttons too. Furthermore, added a dynamic note beside pagination "Showing 1 to 4 of 4 Records"



My AutoGrid.ts :-

JavaScript
//Imports
import {Component,Input} from '@angular/core';
//Needed for triggering events
import {Subject}    from 'rxjs/Subject';
import {Common}     from './Common';
import {PagedList} from './SearchModel'

@Component({
  selector : 'AutoGrid',//tag name in when calling the component
  templateUrl : './../Html/AutoGrid.html',//path of the HTML
  //pipes : [AutoGridPipe]//link the Pipe
})
    
export class AutoGrid
{
    
    constructor(
        private _common: Common)
    { };

  SortBy : string = "";//This param is used to determine which column to use for sorting
  Direction: number = 1;//1 is ascending -1 is descending

  Pages : any = [];//Dummy array to load the pagination
  Data : any = [];//Main data container
  Width: string;
  pageboxLeft = 2;
  pageboxRight = 2;
  @Input() AllowDelete : boolean= true;//Can a row be deleted
  @Input() Columns : any = [];//Name of the coulmns to display / order
  @Input() AllowSorting : boolean= true;//Allow client side sorting
  @Input() TotalRows : number = 0;//Total number of rows for paging
  @Input() PageSize : number = 0;
  @Input() PageIndex : number = 0;//To control the start page index

  public RowDeleted$ = new Subject<any>();//Subscribe to this to handle delete event
  public PageIndexChanged$ = new Subject<any>();//Subscribe to this to handle "page index change" event
  private parameters: any;
  private URL: string;

  //Main method to load the data
  public FillGrid(_url: string, _parameters: any, _loadPagination: boolean = true)
  {   
      //Check if no pagination required, then display full records
      //if (!_loadPagination) {
      //    _parameters.PageSize = 10000;
      //}
      this.PageSize = _parameters.PageSize;
      this.SortBy = _parameters.SortColumn;
      this.Direction = _parameters.SortOrder == "ASC" ? 1 : -1;
      this.parameters = _parameters;
      this.URL = _url;
      var options = {
          URL: _url,
          postData: _parameters
      };
      this._common.PostApiServiceCall(options)
          .subscribe(data => {
              let pagedListItems: PagedList = data;
              if (pagedListItems != undefined) {
                  this.Data = pagedListItems.DataList;
                  this.TotalRows = pagedListItems.TotalRecords;
                  //if (_loadPagination) {
                      this.SetTotalPages();
                      this.SetPagination();
                  //}
              }
          });
  }
  OnDeleteRow(Row2Delete:any)
  {//private method to raise RowDeleted
    this.RowDeleted$.next(Row2Delete);
    //client side delete for data can be done here
  }
  OnPageIndexChange(index: number)
  {//private method to raise RowDeleted
    this.PageIndex = index-1;
    this.Data = [];
    this.PageIndexChanged$.next(index - 1);
    this.parameters.PageNo = index;
    this.FillGrid(this.URL, this.parameters,false);
  }
  SetTotalPages(){
    //used for pagination style
      let totalPages: any = Math.ceil((this.TotalRows / this.PageSize) + 4);
      this.Width = ((totalPages * 38) + totalPages * 2) + "px";
  }
  SetPagination() {
      this.Pages = [];
      let totalPages: any = Math.ceil(this.TotalRows / this.PageSize);

      var boxRight = this.pageboxRight, boxLeft = this.pageboxLeft;
      for (let m = this.PageIndex; m >= (this.PageIndex - this.pageboxLeft); m--) {
          if (m < 0) {
              boxRight = boxRight + 1;
              boxLeft = boxLeft - 1;
          }
      }
      for (let m = this.PageIndex; m <= (this.PageIndex + this.pageboxRight); m++) {
          if (m >= totalPages) {
              boxLeft = boxLeft + 1;
              boxRight = boxRight - 1;
          }
      }

      if (totalPages >= (boxLeft + boxRight + 1)) {
          let j = 0;
          while ((this.Pages.length < (boxLeft + boxRight + 1)) && j < totalPages) {
              if ((this.PageIndex - boxLeft) >= 0 && j >= (this.PageIndex - boxLeft) && j <= this.PageIndex) {
                  this.Pages.push(j + 1);
              }
              else if ((this.PageIndex + boxRight) <= totalPages && j <= (this.PageIndex + boxRight) && j >= this.PageIndex) {
                  this.Pages.push(j + 1);
              }
              j++;
          }
      }
      else
      {
          for (let i = 0; i < totalPages; i++)
              this.Pages.push(i + 1);
      }
  }
  OnNextPage() {
      let totalPages: any = Math.ceil(this.TotalRows / this.PageSize);
      if ((this.PageIndex + 1) == totalPages)
          return
      else {
          this.PageIndex = (this.PageIndex + 1);
          this.OnPageIndexChange(this.PageIndex+1);
      }
  }
  OnPreviousPage() {
      if ((this.PageIndex - 1) < 0)
          return;
      else {
          this.PageIndex = (this.PageIndex - 1);
          this.OnPageIndexChange(this.PageIndex + 1);
      }
  }
  OnLastPage()
  { 
      let totalPages: any = Math.ceil(this.TotalRows / this.PageSize);
      if ((this.PageIndex) == (totalPages) - 1)
          return;
      else {
          this.PageIndex = (totalPages) - 1;
          this.OnPageIndexChange(this.PageIndex + 1);
      }
  }
  OnFirstPage() {
      if (this.PageIndex == 0)
          return;
      else {
          this.PageIndex = 0;
          this.OnPageIndexChange(this.PageIndex + 1);
      }
  }
  
   Sort(key:string,dir:number){
     //Change the sorting criteria
       this.SortBy = key;
       this.Direction = dir;
       this.parameters.SortColumn = this.SortBy;
       this.parameters.SortOrder = this.Direction==1?"ASC":"DESC";
       this.FillGrid(this.URL, this.parameters,false);
   }
}





My AutoGrid.html:


HTML
<!--Just to give the pagination a better look-->
<style>
    .nav {
        border: solid 1px #777;
        float: left;
        padding: 8px;
        margin: 1px;
        width: 38px;
        text-align: center;
    }
    .navColoured {
        border: solid 1px #777;
        float: left;
        padding: 8px;
        margin: 1px;
        width: 38px;
        text-align: center;
        background-color:gray;
    }
</style>
<!--End of style-->
<table class="table">
    <tr>
        <!--Generate column names ... loop on columns array-->
        <th *ngFor="let col of Columns">
            {{col.colName}}
            <a style="cursor: pointer;" [hidden]="!((SortBy!=col.colName) && AllowSorting && col.sortable)" (click)="Sort(col.colName,-1)"></a>
            <a style="cursor: pointer;" [hidden]="!((Direction==1 && SortBy==col.colName) && AllowSorting && col.sortable)" (click)="Sort(col.colName,-1)"></a>
            <a style="cursor: pointer;" [hidden]="!((Direction==-1 && SortBy==col.colName) && AllowSorting && col.sortable)" (click)="Sort(col.colName,1)"></a>
        </th>
        <!--For the delete link-->
        <th [hidden]="!AllowDelete"></th>
    </tr>
    <!--Loop on the data-->
    <tr *ngFor="let c of Data">
        <td *ngFor="let col of Columns">{{c[col.colName]}}</td>
        <!--show delete if enabled, and pass the whole row to OnDeleteRow-->
        <td [hidden]="!AllowDelete"><a (click)="OnDeleteRow(c)">X</a></td>
    </tr>
</table>
<!--Pagination-->
<table class="table">
    <tr>
        <td>
            <div>Showing {{(PageSize * (PageIndex)) + 1}} to {{PageSize * (PageIndex + 1)>TotalRows?TotalRows:PageSize * (PageIndex + 1)}} of {{TotalRows}} Records</div>
            <div style="margin:0px auto;" [style.width]="Width">
                <div class="nav" [hidden]="Pages.length==0">
                    <a style="cursor: pointer;" (click)="OnFirstPage()">First</a>
                </div>
                <div class="nav" [hidden]="Pages.length==0">
                    <a style="cursor: pointer;" (click)="OnPreviousPage()">Prev</a>
                </div>
                <!--Width is calculated based on number of pages, to make it center-->
                <div *ngFor="let pageIndex of Pages;let i = index;" [ngClass]="!(PageIndex+1!=pageIndex)?'navColoured':'nav'">
                    <!--If this is the current page, page number displayed as a text only-->
                    <span style="cursor: pointer;color:white;" [hidden]="PageIndex+1!=pageIndex">{{pageIndex}}</span>
                    <!--Page number dispalyed as a link, which call OnPageIndexChange and pass the new PageIndex + 1 -->
                    <a style="cursor: pointer;" [hidden]="PageIndex+1==pageIndex" (click)="OnPageIndexChange(pageIndex)">{{pageIndex}}</a>
                </div>
                <div class="nav" [hidden]="Pages.length==0">
                    <a style="cursor: pointer;" (click)="OnNextPage()">Next</a>
                </div>
                <div class="nav" [hidden]="Pages.length==0">
                    <a style="cursor: pointer;" (click)="OnLastPage()">Last</a>
                </div>
            </div>
        </td>
    </tr>
</table>




My Main component :

JavaScript
//ViewChild Needed whenever you want to access a child component property or method
import { Component, ViewChild, NgModule } from '@angular/core';
import { HttpModule } from "@angular/http";
import { BrowserModule } from '@angular/platform-browser';
import { Configuration } from "./siteconfig";
import { AutoGrid } from './AutoGrid';
import { Common } from './Common';
import { PagedList } from './SearchModel'

@Component({
    selector: 'searchComponent',
    template: `
           <AutoGrid
           [Columns]="Columns2Display"
           [AllowDelete]="false">
           </AutoGrid>`,
})
class SearchComponent {

    //Parameter list to initialize in the beginning. PageNo, PageSize, SortColumn and SortOrder columns are mandatory.
    //parameterList: any = { "Landmark": "", "PropertyTypeId": 0, "PageNo": 1, "PageSize": 1, "SortColumn": "LandMark", "SortOrder": "ASC" }
    parameterList: any = { "Landmark": "", "PropertyTypeId": 0, "PageNo": 1, "PageSize": 5, "SortColumn": "LandMark", "SortOrder": "ASC" }
    //Columns to display, enable / disalble sort
    //Basically any column base configuration needed, can be added here
    //Such as Display name, column Icon ....
    Columns2Display: any = [
        { colName: "PropertyId", sortable: false },
       // { colName: "PropertyTypeId", sortable: false },
        { colName: "PropertyType", sortable: true },
        { colName: "LandMark", sortable: true },
        { colName: "TypeDescription", sortable: false },
        { colName: "EffectiveDate", sortable: true },
        { colName: "CreatedDate", sortable: true }];

    //Through this we can access the child component through _AutoGrid
    @ViewChild(AutoGrid) private _AutoGrid: AutoGrid;
    
    //Load the data into the child component
    //Cannot be done inside constructor as you don't have access to ViewChild in constructor
    ngOnInit() {
            //Fill Grid method with parameters URL and Parameterlist
            this._AutoGrid.FillGrid("Sample/SearchProperty", this.parameterList);
    }

}

@NgModule({
    imports: [BrowserModule, HttpModule],
    declarations: [SearchComponent, AutoGrid],
    bootstrap: [SearchComponent],
    providers: [Configuration, Common]
})
class SearchModule { }

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(SearchModule);




My Stored Procedure for Reference:

SQL
CREATE PROCEDURE [dbo].[SearchProperty] 
	-- Add the parameters for the stored procedure here
	@PropertyTypeId INT 
	,@PropertyLandmark VARCHAR(50)
	,@PageNo INT 
	,@PageSize INT
	,@SortColumn VARCHAR(50)
	,@SortOrder VARCHAR(5)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON; 

	BEGIN TRY

		DECLARE @OrderBy VARCHAR(55);
		DECLARE @FirstRec INT;
		DECLARE @LastRec INT;
		DECLARE @TotalRecords INT;
 
		SET @PageNo = ISNULL(@PageNo,1);
		SET @PageSize = ISNULL(@PageSize,10);

		SET @FirstRec = ( @PageNo - 1 ) * @PageSize;
		SET @LastRec = ( @PageNo * @PageSize + 1 );

		SELECT 
			@TotalRecords = COUNT(1) 
		FROM Property P
		JOIN PropertyType PT ON P.PropertyTypeId = PT.PropertyTypeId
		WHERE
			(@PropertyTypeId IS NULL OR @PropertyTypeId = 0  OR P.PropertyTypeId = @PropertyTypeId)
		AND (@PropertyLandmark IS NULL OR @PropertyLandmark = '' OR P.PropertyLandmark = @PropertyLandmark)

		; WITH CTE_Results
		AS (
			SELECT ROW_NUMBER() OVER (ORDER BY
				CASE WHEN @SortColumn = 'Landmark' AND @SortOrder = 'ASC'  THEN PropertyLandmark
					END ASC,
				CASE WHEN @SortColumn = 'Landmark' AND @SortOrder = 'DESC' THEN PropertyLandmark
					END DESC, 
 
				CASE WHEN @SortColumn = 'PropertyType' AND @SortOrder = 'ASC'  THEN TypeDescription
					END ASC,
				CASE WHEN @SortColumn = 'PropertyType' AND @SortOrder = 'DESC' THEN TypeDescription
					END DESC, 
 
				CASE WHEN @SortColumn = 'EffectiveDate' AND @SortOrder = 'ASC'  THEN EffectiveDate
					END ASC,
				CASE WHEN @SortColumn = 'EffectiveDate' AND @SortOrder = 'DESC' THEN EffectiveDate
					END DESC, 
 
				CASE WHEN @SortColumn = 'CreatedDate' AND @SortOrder = 'ASC'  THEN CreatedDate
					END ASC,
				CASE WHEN @SortColumn = 'CreatedDate' AND @SortOrder = 'DESC' THEN CreatedDate
					END DESC 
				) AS ROWNUM,
				PropertyId
				,PropertyLandmark
				,PT.TypeDescription
				,EffectiveDate
				,CreatedDate				
			FROM Property P
			JOIN PropertyType PT ON P.PropertyTypeId = PT.PropertyTypeId
			WHERE
				(@PropertyTypeId IS NULL OR @PropertyTypeId = 0  OR P.PropertyTypeId = @PropertyTypeId)
			AND (@PropertyLandmark IS NULL OR @PropertyLandmark = '' OR P.PropertyLandmark = @PropertyLandmark)
		)

		SELECT
			PropertyId
			,PropertyLandmark
			,TypeDescription
			,EffectiveDate
			,CreatedDate
			,@TotalRecords AS TotalRecords
		FROM CTE_Results AS CPC
		WHERE
			ROWNUM > @FirstRec 
		AND ROWNUM < @LastRec
		ORDER BY ROWNUM ASC

	END TRY
	BEGIN CATCH
		-- Execute error retrieval routine.  
		EXECUTE LogException;  
	END CATCH;
END

GeneralRe: Grid Component Code made more efficient through api service call, pagination and server side sorting Pin
Girish Deshmukh8-Aug-17 20:55
Girish Deshmukh8-Aug-17 20:55 
GeneralRe: Grid Component Code made more efficient through api service call, pagination and server side sorting Pin
Sonesh Singh5-Jan-18 2:19
Sonesh Singh5-Jan-18 2:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.