Posts on this Category



Creating a NodeJS project with Express

Express is one of the most popular npm packages out there, it’s basically a NodeJS web application framework that provides lots of functionalities and helps you to manage everything and organize your app into MVC on the back-end, and it’s very easy to get started with.

To use Express you first need to have NodeJS installed (obviously), if you don’t have it yet click here and download the appropriate version for your OS. With nodejs installed you can now create your your project and start using express, in this tutorial I’m just going to cover how to create the project, but in the future I’ll probably write more about it.

Express has a tool called express-generator that is used to create the project’s basic structure, to install it just use the command:

npm install express-generator -g

Now that we’ve installed it globally we’re ready to create the project, open your terminal and navigate to the folder where you want to put your project, then simply run the command:

express myFirstExpressApp

Done! Now you have a folder called myFirstExpressApp (or any other name you’ve chosen), if you go inside it you’ll see the project files and the following folder structure:

Express Basic Project Structure
Express Basic Project Structure

Automatically Mapping JPA Entities with Netbeans

Creating the JPA entities manually can be really time consuming, specially if you’re working with a huge database with hundreds of tables. Luckily, Netbeans IDE can automatically create the entities for us, if you want to see how just follow the instructions bellow:

1 – Right click on your package -> New -> Entity Classes from Database:

New Entity Classes From Database
New Entity Classes From Database

2 – A new window will show up, but before you proceed you have to create a data source:

New Data Source
New Data Source

3 – Name it as you like and click on New Database Connection:

New Database Connection
New Database Connection

3 – You’ll be asked to select the database driver and also to provide the connection info, after that just click next and finish:

Providing Connection Info
Providing Connection Info

4 – Now you can already see a list containing your database tables, select the ones you want and click next, another screen with some options will show up but you don’t need to change anything, just hit next again and finish:

Selecting the Tables
Selecting the Tables

5 – That’s it! As you can see you already have the entities:

New Entities
New Entities

Improve Performance by Increasing Glassfish Memory

When a Glassfish domain is created it already comes with a default set of JVM options (including memory related options), as you keep working on your project your application will increasingly grow and consume more memory, until it reaches the point where the default Glassfish memory configuration isn’t appropriate to run your app anymore. If you are facing this problem you can easily increase the memory by following the instructions bellow:

1 – Open the glassfish console on your browser and click on server-config:

Glassfish Console
Glassfish Console

2 – Then click on JVM Settings:

Glassfish server-config screen
Glassfish server-config screen

3 – On the JVM Options tab these are the two options you may want to change: XX:MaxPermSize and Xmx.

Glassfish JVM Options
Glassfish JVM Options

As long as you have memory available on your server you can put any size you want here. After the modifications you just need to restart your server and you’re done!

Tutorial: Creating an Angular2 Autocomplete

Angular 2 Autocomplete
Angular 2 Autocomplete

Before we begin I just want to say that I’m not going to use any third-party component for this tutorial, I’m going to create an autocomplete from scratch, my goal is to just make it show the suggestions and allow the user to select one, but if you need more advanced features feel free to comment, I’ll do what I can to help you.

With that in mind, let’s start by creating our class, just copy/paste the code bellow:

export class AutocompleteComponent {
    public query = '';
    public countries = [ "Albania","Andorra","Armenia","Austria","Azerbaijan","Belarus",
                        "Belgium","Bosnia & Herzegovina","Bulgaria","Croatia","Cyprus",
                        "Czech Republic","Denmark","Estonia","Finland","France","Georgia",
                        "Germany","Greece","Hungary","Iceland","Ireland","Italy","Kosovo",
                        "Latvia","Liechtenstein","Lithuania","Luxembourg","Macedonia","Malta",
                        "Moldova","Monaco","Montenegro","Netherlands","Norway","Poland",
                        "Portugal","Romania","Russia","San Marino","Serbia","Slovakia","Slovenia",
                        "Spain","Sweden","Switzerland","Turkey","Ukraine","United Kingdom","Vatican City"];
    public filteredList = [];
    public elementRef;
 
    constructor(myElement: ElementRef) {
        this.elementRef = myElement;
    }
}

As you can see I’ve already added the data to my class, as I’m trying to make it simple it’s just an array of countries, but of course in a real case scenario the data would come from your database or via web service, also it wouldn’t be placed inside the component, it would be passed to it, this way the component could be reused with other data in other parts of the application.

I’ve also created the variables query and filteredList, the first one will hold the string typed by the user, and the second is where I’m going to store the suggestions being displayed by the component, its value will constantly change as the user types on the input. There is also the constructor where I’m setting the elementRef value, but I’ll get to that variable in a moment.

Now let’s create the methods to filter the data and select the item:

filter() {
    if (this.query !== ""){
        this.filteredList = this.countries.filter(function(el){
            return el.toLowerCase().indexOf(this.query.toLowerCase()) > -1;
        }.bind(this));
    }else{
        this.filteredList = [];
    }
}
 
select(item){
    this.query = item;
    this.filteredList = [];
}

These two functions are very straightforward, the filter() function uses the query variable to filter the countries, then it stores the result in the filteredList.

The select() is even simpler, I’m just assigning the selected item to the query variable in order to make it appear on the input, and to make the suggestions list disappear I’m removing everything from the filteredList.

Ok, we already have the two most important functions to make our component work, now we can create the template:

@Component({
    selector: 'autocomplete',
    template: `
        <div class="container" >
            <div class="input-field col s12">
              <input id="country" type="text" class="validate filter-input" [(ngModel)]=query (keyup)=filter()>
              <label for="country">Country</label>
            </div>
            <div class="suggestions" *ngIf="filteredList.length > 0">
                <ul *ngFor="#item of filteredList" >
                    <li >
                        <a (click)="select(item)">{{item}}</a>
                    </li>
                </ul>
            </div>
        </div>  	
        `
})

Note that I’ve used some different css classes here, some of them I created myself and some are from materialize, if you want to use them just add to your project the link to their css and js files.

At this point your autocomplete is already working, if you run your project you’ll see a result similar to the gif at the beginning of this tutorial, but there’s still a small problem we have to fix, note that once the suggestions list shows up you have to either erase the text from the input or select one to make the them disappear. The problem is that the user should be able to get rid of the suggestions by clicking anywhere other than the list, and to be able to do that we have to detect clicks outside the our component, more info here.

Remember the elementRef variable we saw in the constructor? Now we’re going to use it, the follwoing method tells whether the click occured in the component or outside it:

handleClick(event){
   var clickedComponent = event.target;
   var inside = false;
   do {
       if (clickedComponent === this.elementRef.nativeElement) {
           inside = true;
       }
      clickedComponent = clickedComponent.parentNode;
   } while (clickedComponent);
    if(!inside){
        this.filteredList = [];
    }
}

The function just gets the clicked component, navigates between its parent nodes and checks if one of them is the elementRef.nativeElement (which is our component), if it’s true the items from the filteredList are deleted in order to make the list disappear. Now we have to bind this method to the (document:click) event, this is how you can do it:

@Component({
    selector: 'autocomplete',
    host: {
        '(document:click)': 'handleClick($event)',
    },
    template: //TEMPLATE CODE HERE
})

That’s it!! As I said if you need more features or if you have any doubts just leave a comment, I’ll be glad to help!

Angular2 Tutorial: Detecting Clicks Outside the Component

Angular2 click detection
Angular2 click detection

Sometimes there is a need to detect whether the user is clicking inside or outside our angular2 component, specially if your component has a dropdown element, in this case you need to know exactly where the click occurred in order to perform the right action. In this tutorial I’m going to demonstrate with angular 2 a very easy way to determine if the click happened outside the component or not.

Let’s start by creating this very simple component:

import {Component, ElementRef} from 'angular2/core';
 
@Component({
    selector: 'click-detection-component',
    template: `
    	<div style="width:100px;height:60px;background-color:#f1f1f1"></div>
    	`
})
 
export class ClickDetectionComponent {
}

Nothing special here, it just renders a rectangle on the screen. Now my goal will be to show a different message when the click occurs inside and outside this rectangle, to do that we have to create a function to check if the clicked component belongs to my current angular2 component or not:

export class ClickDetectionComponent {
   public elementRef;
 
   constructor(myElement: ElementRef) {
       this.elementRef = myElement;
   }
 
   handleClick(event){
       var clickedComponent = event.target;
       var inside = false;
       do {
           if (clickedComponent === this.elementRef.nativeElement) {
               inside = true;
           }
           clickedComponent = clickedComponent.parentNode;
       } while (clickedComponent);
       if(inside){
           console.log('inside');
       }else{
           console.log('outside');
       }
   }
}

Here’s what is happening in this function: First I’m getting the clicked component from my event using event.target, then I’m navigating between its parent nodes checking is one of them is my elementRef.nativeElement, if it is, it means that the user clicked inside the component, otherwise it was outside.

Now comes the tricky part, if I bind this function to the div click event it will only be called when the user clicks on the div, therefore how am I going to be able to detect the clicks that occurs outside? To solve that I’m going to use the (document:click) event, this way the function will be called no matter where the user clicks.

You can add this event to your component like this:

@Component({
    selector: 'click-detection-component',
    host: {
        '(document:click)': 'handleClick($event)',
    },
    template: `
    	<div style="width:100px;height:60px;background-color:#f1f1f1"></div>
    	`
})

Perfect! Now if you run your project you can see the messages on the console telling whether the component was clicked or not.

Hope you enjoyed the tutorial, just leave a comment if you have any doubts.

Tutorial: Sorting and Filtering a ReactJS Datatable

ReactJS Datatable with Sort and Filter
ReactJS Datatable with Sort and Filter

A few months ago I’ve made this post about how to create a reactjs datatable using the FixedDataTable module, I didn’t cover much, I just gave a simple example explaining how to populate the table with JSON data. Today we’re going a little further, continuing from where I stopped I’m going to show you how to sort and filter the data on this datatable.

Before we begin I’ll reorganize the code a little bit, let’s put all our datatable related code in a different file, I’ll name it myTable.js, its content should look like this:

import React from 'react';
import {Table, Column, Cell} from 'fixed-data-table';
 
class MyTable extends React.Component {
 
  constructor(props) {
    super(props);
    this.state = {
      rows : [{"id":1,"first_name":"William","last_name":"Elliott","email":"welliott0@wisc.edu",
             "country":"Argentina","ip_address":"247.180.226.89"},
              {"id":2,"first_name":"Carl","last_name":"Ross","email":"cross1@mlb.com",
             "country":"South Africa","ip_address":"27.146.70.36"},
              {"id":3,"first_name":"Jeremy","last_name":"Scott","email":"jscott2@cbsnews.com",
             "country":"Colombia","ip_address":"103.52.74.225"},
             // more data
    };
  }
 
  render() {
      return <Table
        height={40+((this.state.rows.length+1) * 30)}
        width={1150}
        rowsCount={this.state.rows.length}
        rowHeight={30}
        headerHeight={30}
        rowGetter={function(rowIndex) {return this.state.rows[rowIndex]; }.bind(this)}>
        <Column dataKey="id" width={50} label="Id" />
        <Column dataKey="first_name" width={200} label="First Name" />
        <Column  dataKey="last_name" width={200} label="Last Name" />
        <Column  dataKey="email" width={400} label="e-mail" />
        <Column  dataKey="country" width={300} label="Country" />
      </Table>;
  }
}
 
module.exports = MyTable;

I’m just making it because it’s a good practice, in this example it won’t make much difference, but in an application with multiple components it would get really messy if you put everything on the main.js.

After isolating the datatable component our main.js is much cleaner:

import MyTable from './myTable';
import React from 'react';
import ReactDOM from 'react-dom';
 
ReactDOM.render(<MyTable/>,document.getElementById('example'));

If you run the project now you should see the exact same result as before, now let’s start adding some features to this table.

Filtering the data

We have to make a few changes in the constructor in order to add the filter functionality:

constructor(props) {
  super(props);
  this.rows = //json data
  this.state = {
    filteredDataList: this.rows
  };
}

As you can see I took the rows variable out of the state and replaced it with filteredDataList, now you must think of rows as our data source, like a database table or a web service it shouldn’t be part of our state, what should be is the data we are actually displaying on the table, which will be the filteredDataList. Initially it will have the exact same data as the rows variable, but as the user starts filtering, its value will change.

After this, the attributes height, rowsCount and rowGetter of our table are still referencing the rows variable, as the table won’t interact directly with this variable anymore, they should be changed to reference the filteredDataList.

Now let’s add to our class the methods responsible for the filtering:

_renderHeader(label, cellDataKey) {
  return <div>
        <span>{label}</span>
          <div>
            <br />
            <input style={{width:90+'%'}} onChange={this._onFilterChange.bind(this, cellDataKey)}/>
          </div>
      </div>;
}
 
_onFilterChange(cellDataKey, event) {
  if (!event.target.value) {
    this.setState({
      filteredDataList: this.rows,
    });
  }
  var filterBy = event.target.value.toString().toLowerCase();
  var size = this.rows.length;
  var filteredList = [];
  for (var index = 0; index < size; index++) {
    var v = this.rows[index][cellDataKey];
    if (v.toString().toLowerCase().indexOf(filterBy) !== -1) {
      filteredList.push(this.rows[index]);
    }
  }
  this.setState({
    filteredDataList: filteredList,
  });
}

The _renderHeader() function tells the Column what should be rendered on it’s header, in this case it’s just adding an input so the user can type and filter the data, on its onChange event I’m calling the function _onFilterChange which will actually do the filtering and update the filteredDataList value.

Lastly we have to call the _renderHeader function on our columns like this:

<Column dataKey="id" width={50} label="id"  
     headerRenderer={this._renderHeader.bind(this)}/>

Note that I’ve used bind() to call the function _renderHeader(), it’s really important that you do exactly like that, otherwise you will come across the problem described here.

Now you can run your project, if you did everything right you should see an input bellow the label on the header, if you type something in there you’ll see that the filter is already working.

Making the Columns Sortable

In order to use the sort feature we have to add two more attributes to the state: sortBy and sortDir:

 
constructor(props) {
  super(props);
  this.rows = //json data
  this.state = {
    filteredDataList: this.rows,
    sortBy: 'id',
    sortDir: null
  };
}

The first is responsible for telling by which column our datatable is currently being sorted by, it’s being initialized with the column id, and the second is just for allowing us to control whether it’s ASC or DESC.

We also have to modify the _renderHeader() a little bit:

_renderHeader(label, cellDataKey) {
  return <div>
        <a onClick={this._sortRowsBy.bind(this, cellDataKey)}>{label}</a>
          <div>
            <br />
            <input style={{width:90+'%'}} onChange={this._onFilterChange.bind(this, cellDataKey)}/>
          </div>
      </div>;
}

I just replaced the span with a link where the user will click to sort the table, on the onClick event it calls the following function:

_sortRowsBy(cellDataKey) {
  var sortDir = this.state.sortDir;
  var sortBy = cellDataKey;
  if (sortBy === this.state.sortBy) {
    sortDir = this.state.sortDir === 'ASC' ? 'DESC' : 'ASC';
  } else {
    sortDir = 'DESC';
  }
  var rows = this.state.filteredDataList.slice();
  rows.sort((a, b) => {
    var sortVal = 0;
    if (a[sortBy] > b[sortBy]) {
      sortVal = 1;
    }
    if (a[sortBy] < b[sortBy]) {
      sortVal = -1;
    }
 
    if (sortDir === 'DESC') {
      sortVal = sortVal * -1;
    }
    return sortVal;
  });
 
  this.setState({sortBy, sortDir, filteredDataList : rows});
}

This function is responsible for the sorting, if you take a look at the code you’ll see that in order to “decide” how the table should be sorted it uses and modifies the two new variables we added to the state, at the end it sets the state again with the modified values.

Now add this code to your render() function, right before returning your component:

var sortDirArrow = '';
if (this.state.sortDir !== null){
  sortDirArrow = this.state.sortDir === 'DESC' ? ' ↓' : ' ↑';
}

This code is just for controlling the arrow that will be displayed in front of the column label. Don’t forget to add the logic to your column label attribute as well, otherwise the arrow won’t be displayed.

<Column dataKey="id" width={50} 
  label={'id' + (this.state.sortBy === 'id' ? sortDirArrow : '')}
  headerRenderer={this._renderHeader.bind(this)}/>

Ok, now we are done with the sorting and filtering, if you run your project the result should be exactly the same as the gif at the beginning of this post.

That’s it! Hope you enjoyed the tutorial, just leave a comment if you have any doubts.

ReactJS Error: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

This is a very common error for reactjs beginners, if you are facing this error it means your render method is modifying the state of your component, causing it to re-render, which then will modify it again and so on. You are dealing with an infinite loop here, if you take a look at your console (before your browser crashes) you’ll see something like this:

setState(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
setState(…): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

Before I explain how to solve it I’ll show you the most probable reason why it’s happening, let’s analyze the following component:

class ErrorSimulation extends React.Component {
 
  constructor(props) {
    super(props);
    this.state = {
      x : 1
    };
  }
 
  _changeValue(newValue){
    this.setState({newValue});
  }
 
  render() {
    return <a onClick={this._changeValue(2)}>Change Value</a>
  }
}

Note that the render() method is calling the function _changeValue(), if you take a look at this function you’ll see that it’s modifying the state. Nothing wrong, right? This should be OK, otherwise how would the component be able to modify it’s own state? Well, the problem here is the way we call the function, by doing it like I did in this example the function _changeValue() will actually be called and executed right away during the state transition, this will cause the problem. We can solve that by changing a little bit the way we call the function.

Instead of doing this:

<a onClick={this._changeValue(2)}>Change Value</a>

we call it like this:

<a onClick={this._changeValue.bind(2)}>Change Value</a>

By using bind() your function won’t be called during the state transition anymore, it will complete the process and leave the function to be called later, this will prevent the problem from happening.

Angular2 Tutorial: Creating Custom Pipes

Angular 2 Pipes provide us a very simple way to transform/format the data displayed by our application, there are some built-in pipes we can use, but sometimes they don’t meet our needs, that’s when we have to create custom pipes. This will be a very quick tutorial in which I’ll give you an example of how you can create your own pipes.

I’m assuming you already have your angular2 project, but if you don’t, just follow the instructions on the official site to create a starter project. Make sure the project is working before you proceed.

As an example I’m going to create a pipe to limit the amount of characters on a string, let’s assume you have limited space on your page and there is no way for you to display the entire text, you’ll just provide the maximum amount of characters and the pipe will take care of the rest, every time you come across this situation you can use this pipe to make the text fit on the space you have available.

Let’s start by creating in our app folder a file called maxLength.pipe.ts, copy/paste the following code into it:

import {Pipe} from 'angular2/core';
 
@Pipe({
    name: 'maxLength'
})
export class MaxLengthPipe {
    transform(val, args) {
        if (val.length > 30){
            return val.substring(0, 30)+'...';    
        }else{
            return val;
        }
    }
}

Perfect, you already have a pipe!! All you had to do was to create a class and put the @Pipe decorator on it, but to make it work we also have to implement the transform function, that’s where we are going to put our logic. In this simple example I’m just checking if my text has a length greater than 30, if it does I’m returning the first 30 characters.

That’s enough for us to be able to use our pipe, open your app.component.ts and paste the following code:

import {Component} from 'angular2/core';
import {MaxLengthPipe} from './maxLength.pipe';
 
@Component({
    selector: 'my-app',
    template: `<p>{{value | maxLength}}</p>`,
    pipes: [MaxLengthPipe]
})
 
export class AppComponent { 
    public value = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vel dui '
                  +'at sem placerat dictum dictum placerat est. Mauris pretium mattis nulla '
                  + 'vel suscipit.Vestibulum laoreet congue erat, eget bibendum justarius id';   
}

That’s the simplest possible example, I have a class with just one attribute which will store my text. Note how I used the pipe in the template, I just wrote the name of my variable followed by the pipe name we specified in the @Pipe decorator, which in this case was maxLength.

If you run the project you’ll see that it’s already working, but we can improve it a little bit more, instead of always returning the first 30 characters, we can pass a parameter to the pipe telling how many characters we want. To do that we have to modify our transform function, everywhere we were using the number 30 we have to replace it by args[0], this is how it should look like:

transform(val, args) {
    if (val.length > args[0]){
        return val.substring(0, args[0])+'...';    
    }else{
        return val;
    }
}

Then in the app.component.js you can pass the parameter like this:

{{value | maxLength : 30}}

That’s it!! Hope you enjoyed the tutorial, leave a comment if you have any doubts.

Tutorial: Angular 2 Datatable with Sorting, Filtering and Resizable Columns

In this tutorial I’m going to show you one of the datatable solutions available for Angular 2, it’s called ag-Grid and it’s available not only for angular2, but also for other frameworks like Angular 1 and React. It’s a really complete datatable, it has lots of features that I definitely want to explore in other tutorials, but in this one I’ll try to keep it as simple as possible, my goal is to just make it display the data and enable the sorting, filtering and the resizable columns features. Maybe in the future I’ll write a PART 2 of this tutorial explaining how to add some more complex functionality. If you don’t want to use ag-grid take a look at this post.

I’m assuming you already have your Angular 2 project ready, but if you don’t just follow the instructions on this link to set up your environment, it’s really easy and straightforward, all you need to do is to create three configurations files: tsconfig.json, typings.json and package.json, make sure you have all of them before you continue.

Now let’s add the ag-grid to the project, to do that you have to add these two lines to the dependencies list on your package.json:

{
  "dependencies": {
    "ag-grid": "3.3.x",
    "ag-grid-ng2": "3.3.x"
    ...
  },
}

Run npm install to download and install the dependencies, when it completes we’ll be ready to start writing some code!

Open your project folder and create another one inside called app, that’s where we’re going to put all our Angular2 related code. The first file we are going to create on this folder is the app.component.ts, it should contain the following code, just copy and paste it into the file:

import {Component} from 'angular2/core';
import {AgGridNg2} from 'ag-grid-ng2/main';
 
@Component({
    selector: 'my-datatable',
    directives: [AgGridNg2],
    template: `
         <ag-grid-ng2 #agGrid style="height:100%;width:845px" class="ag-fresh"
            [gridOptions]="gridOptions">
         </ag-grid-ng2 >
     `
})
 
export class AppComponent { 
    myRowData = [
        {"name":"Ronald Bowman","country":"China","city":"Lutou","email":"rbowman0@spotify.com"},
        {"name":"Pamela Hill","country":"Russia","city":"Krylovskaya","email":"phill1@symantec.com"},
        {"name":"Robin Andrews","country":"Ukraine","city":"Korop","email":"randrews2@photobucket.com"},
        {"name":"Peter Kim","country":"Mexico","city":"San Jose","email":"pkim3@theatlantic.com"},
        {"name":"Carol Foster","country":"Mexico","city":"El Aguacate","email":"cfoster8@intel.com"},
        {"name":"Jimmy Burke","country":"Indonesia","city":"Banjarsari","email":"jburke9@over-blog.com"},
        {"name":"Jonathan Crawford","country":"Peru","city":"Alca","email":"jcrawforda@deliciousdays.com"},
        {"name":"Donald Montgomery","country":"Poland","city":"Działoszyce","email":"dmontgomeryb@google.com.br"},
        {"name":"Donna Shaw","country":"Japan","city":"Akune","email":"dshawc@chronoengine.com"},
        {"name":"Helen King","country":"United States","city":"Hollywood","email":"hkingd@devhub.com"},
        {"name":"Walter Myers","country":"China","city":"a ndaowa n", "email":"wmyerse@state.tx.us"},
        {"name":" Alice Collins","country":"Papua Nw  Guine a", "city":"Mendi","email":"acollinsf@npr.org"},
        {"name":"Anne Richards","country":"China","city":"Koramlik","email":"arichardsu@vinaora.com"},
        {"name":"Randy Miller","country":"Indonesia","city":"Trenggulunan","email":"rmillerv@oakley.com"},
        {"name":"Phillip Adams","country":"Bahamas","city":"Duncan Town","email":"padamsw@lycos.com"},
        {"name":"Nicholas Allen","country":"Philippines","city":"Bautista","email":"nallenx@aboutads.info"},
        {"name":"Lisa Willis","country":"Thailand","city":"Lat Yao","email":"lwillisy@istockphoto.com"},
        {"name":"Jeffrey Castillo","country":"Indonesia","city":"Karangsari","email":"jcastilloz@washington.edu"},
        {"name":"Michael Carpenter","country":"Colombia","city":"Cali","email":"mcarpenter13@prlog.org"},
        {"name":"Roger Lee","country":"France","city":"Courtaboeuf","email":"rlee14@earthlink.net"},
        {"name":"Steve Wallace","country":"Russia","city":"Novobeysugskaya","email":"swallace15@cisco.com"},
        {"name":"Shirley Patterson","country":"Peru","city":"La Tinguiña","email":"spatterson16@woothemes.com"},
        {"name":"Nancy Ward","country":"Sweden","city":"Båstad","email":"nward17@mapquest.com"}
    ];
 
    columnDefs = [
        {headerName: 'Name', field: "name", width: 200 },
        {headerName: 'Country', field: "country" ,width:180},
        {headerName: 'City', field: "city" ,width:160},
        {headerName: 'e-mail', field: "email" ,width:300}
    ];
 
    gridOptions = [];
 
    constructor() {
        this.gridOptions = {
            rowData: this.myRowData,
            columnDefs: this.columnDefs,
            enableColResize: true,
            enableSorting: true,
            enableFilter: true
        }   
    }
}

There is quite a lot to explain about this code, I’m going to start with the class AppComponent, that’s where we’re going to put all the parameters and configurations that makes our datatable work, we have three variables on this class: myRowData, columnDefs and gridOptions.

myRowData: This variable will store the data to be displayed on the table, for this example I’m just going to use some JSON data I generated, but in a real case scenario you would get the data from your database or a web service.

columnDefs: This one will store an object containing information about every column of our datatable, I’m just using the attributes headerName to define the column title, field to tell which array attribute will be displayed on the column and width to define the size of each column. Although I’m using only three, there are tons of other attributes you could specify here.

gridOptions: This one just wraps everything up and make it available to the component. It’s being initialized empty, but in the constructor I’m setting its value, besides the rowData and columnDefs I’m also specifying the attributes enableColResize, enaleSorting and enableFilter. They will do exactly what their names suggests, enable the columns resize, sorting and filtering features respectively.

Now we can create our component, to be able to use the directive AgGridNg2 we have import it first with the line import {AgGridNg2} from 'ag-grid-ng2/main, after that all you need to do is to pass the gridOptions to the ag-grid-ng2 component on the template.

Before we write the index.html we’re going to need one more ts file to be able to launch our application, on your app folder create the file main.ts and paste the following code into it:

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component'
 
bootstrap(AppComponent);

Now you can create the index.html file on your project root folder, let’s take a look at the code:

<html>
  <head>
    <title>Datatable</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">    
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <link href="node_modules/ag-grid/dist/styles/ag-grid.css" rel="stylesheet" />
    <link href="node_modules/ag-grid/dist/styles/theme-fresh.css" rel="stylesheet" />
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          },        
          lib: {
            format: 'register',
            defaultExtension: 'js'
          },
          'ag-grid-ng2': {
            defaultExtension: "js"
          },
          'ag-grid': {
            defaultExtension: "js"
          }
        },
        map: {
            'ag-grid-ng2': 'node_modules/ag-grid-ng2',
            'ag-grid': 'node_modules/ag-grid'
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <body>
    <my-datatable>Loading...</my-datatable>
  </body>
</html>

This file will basically be used just to load the necessary scripts and to configure SystemJS to load everything and launch the application. Finally you can use your component here calling it by the selector we specified before: my-datatable.

We’re done!! To run the project open your terminal, navigate to your project folder and run npm start, this should be the result: my-datatable.

Angular 2 Datatable with Sorting, Filtering and Resizable Columns
Angular 2 Datatable with Sorting, Filtering and Resizable Columns