AppDividend
Latest Code Tutorials

Angular 6 Smart Table Example

Angular Table with Sorting, Searching and Pagination

1 945

Get real time updates directly on you device, subscribe now.

In this tutorial, we will see Angular 6 Smart Table Example.  We use the ng2-smart-table library for this example. The ng2-smart-table library provides us sorting, searching and filtering functionalities. So let us start this example.

Angular 6 Smart Table Example.

First, we start our tutorial by installing Angular 6 CLI. If you have already installed, then you can skip the installation.

Step 1: Install Angular 6 project.

npm install -g @angular/cli

If it does not install then try in the administrator mode.

Now, after that, create a new Angular 6 application using the following command.

ng new ngtable

Go into the project directory.

cd ngtable

Start the server by typing the following command.

ng serve --open

Now, one change in Angular 6 is that Angular 6 now depends on TypeScript 2.7 and RxJS 6. So, if you install third-party packages right now, then it is not compatible with Angular 6. In future, all the third-party libraries might upgrade their packages, but right now, it is not compatible with Angular 6.

So, to fill the gap between Angular 6 and third-party packages, we need to install the following library. That is it.

npm i rxjs-compat --save

Step 2: Install the ng2-smart-table library.

Install it via the following command.

npm install --save ng2-smart-table

Inside app.module.ts file, write the following code to register this module inside our Angular application.

// app.module.ts

import { Ng2SmartTableModule } from 'ng2-smart-table';

@NgModule({
  imports: [
    // ...
    
    Ng2SmartTableModule,
    
    // ...
  ],
  declarations: [ ... ]
})
// ...

Step 3: Create a Table Component.

Type the following command to generate the component.

ng g c table

Now, import this component inside app.component.ts file.

// app.component.ts

import { Component } from '@angular/core';
import { TableComponent } from './table/table.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

Write only the following code inside an app.component.html file.

<app-table></app-table>

Save the file and see this URL: http://localhost:4200/ You can see in the page: table works!

Step 4: Create a backend server.

We need the fake data to work with that is why I am using one package called json-server for this tutorial. Okay, so let us install the package using Yarn package manager.

yarn global add json-server

# or

npm install -g json-server

Now we need to create a folder inside src directory called data and in that folder, create one file called db.json. Let us add the following data inside a db.json file.

{
    "characters": [
    {
        "id": "1",
        "name": "Peter Dinklage",
        "age": "45"
    },
    {
        "id": "2",
        "name": "Lina Heady",
        "age": "43"
    },
    {
        "id": "3",
        "name": "Emilia Clarke",
        "age": "30"
    },
    {
        "id": "4",
        "name": "Kit Harrington",
        "age": "30"
    },
    {
        "id": "5",
        "name": "Sean Bean",
        "age": "50"
    }]
}

Now, start the JSON server using the following command.

json-server --watch src/data/db.json --port 4000

Now, we have a server running that can feed the data to our React Bootstrap Application.

Our JSON server is started at port: 4000 and URL is: http://localhost:4000/characters

Step 5: Setup HttpClient.

Related Posts
1 of 9

Angular is full fledge Frontend Framework, so it has already HTTP module. So first let us configure inside app.module.ts file.

// app.module.ts

import { HttpClientModule } from '@angular/common/http';

imports: [
    BrowserModule,
    Ng2SmartTableModule,
    HttpClientModule
 ],

Now, inside table folder, create one file called Table.ts. It is an interface, which tells the Angular application that, which kind of data is on the backend that we need to display at frontend.

// Table.ts

export interface Table {
    id: Number;
    name: String;
    age: Number;
}

Also, inside table folder, create one file called table.service.ts. We are writing the network request code inside this file. Then we import this file inside table.component.ts file and then call service file’s function.

// table.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class TableService {
  constructor(private http: HttpClient) { }
  url = 'http://localhost:4000';
  getCharacters() {
    return this
            .http
            .get(`${this.url}/characters`);
        }
}

Also, we need to import this service file inside app.module.ts.

// app.module.ts

import { TableService } from './table/table.service';

providers: [TableService],

Finally, we need to call the service function from table.component.ts file.

// table.component.ts

import { Component, OnInit } from '@angular/core';
import { TableService } from './table.service';
import { Table } from './Table';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styles: []
})
export class TableComponent implements OnInit {

  characters: Table[];

  constructor(private tservice: TableService) { }

  ngOnInit() {
    this
      .tservice
      .getCharacters()
      .subscribe((data: Table[]) => {
        this.characters = data;
    });
  }

}

Now, finally, write the template code inside a table.component.html file.

<table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Age</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let character of characters">
        <td>{{ character.id }}</td>
        <td>{{ character.name }}</td>
        <td>{{ character.age }}</td>
      </tr>
    </tbody>
</table>

It will output like below image.

Angular 6 Smart Table Example

 

Step 6: Configure the Angular Smart Table.

Now, create the settings object inside table.component.ts file.

This object contains columns that need to be displayed on the table.

// table.component.ts

settings = {
    columns: {
      id: {
        title: 'ID'
      },
      name: {
        title: 'Name'
      },
      age: {
        title: 'Age'
      }
    }
  };

The columns keys contain the column name and title is the table’s column title. Both are different things. We right now only concern about column’s keys and that is id, name, and age. It is same as, the Table.ts properties.

Now, the second property we need to define is a source and the at is our actual data.

Also, now we can write the table.component.html file like this because we are now using the smart table. So we do not need to iterate the loop to display the data.

We can directly use the Directive provided by ng-smart-table and that is <ng-smart-table>

But that component needs two properties.

  1. settings
  2. source

The settings are our columns and source is our data and it is characters.

Now, write the following code inside the table.component.html and remove everything else.

// table.component.html

<ng2-smart-table 
    [settings]="settings" 
    [source]="characters">
</ng2-smart-table>

Save the file and see the browser: http://localhost:4200/

Angular Table Example with Pagination, Sorting and Searching

 

In that table, now you can searching and sorting based on columns.

There are lots of advanced things we can do on this table, but we will see in the upcoming tutorials.

Angular 6 Smart Table Example is over here. Thanks for taking.

1 Comment
  1. Gajanan says

    HI,

    I am getting below error
    Error: The selector “app-root” did not match any elements

Leave A Reply

Your email address will not be published.