AppDividend
Latest Code Tutorials

Angular 8 Smart Table Example Tutorial For Beginners

Angular 8 Table with Sorting, Searching and Pagination

14

In this tutorial, we will see Angular 8 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 8 Smart Table Example.

Angular 8 Smart table is an Angular module to easily display data in a table with a set of built-in features such as filtering, sorting, etc. in a declarative way. While developing this module I made sure to focus on these particular points:

lightweight:

Angular smart-table is less than 4kb minified and has no dependencies other than Angular itself. And you can even reduce its size with a custom build if you are not interested in some of the plugins.

Robust:

Angular smart-table is widely tested which makes the module really stable modular and extensible: The core features can be accessed with the controller API which is created by the top-level directive. Then a set of directives (plugins) allows you to compose your table behavior in a declarative way.

Developer friendly:

The design of the Angular module has been thought carefully and it is really easy to get into the source code to modify/customize the module to best fit your needs.

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

Step 1: Install Angular 8 project.

npm install -g @angular/cli

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

Now, after that, create a new Angular 8 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 8 is that Angular 8 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 8.

In the future, all third-party libraries might upgrade their packages, but right now, it is not compatible with Angular 8.

So, to fill the gap between Angular 8 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 the 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 the 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 on 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 a 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.

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

// app.module.ts

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

imports: [
    BrowserModule,
    Ng2SmartTableModule,
    HttpClientModule
 ],

Now, inside the 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 the frontend.

// Table.ts

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

Also, inside the 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 the table.component.ts file and then call the angular 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 the app.module.ts.

// app.module.ts

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

providers: [TableService],

Finally, we need to call the service function from the 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 the below image.

Angular 6 Smart Table Example

Step 6: Configure 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 the 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 the 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 8 Smart Table Example is over here. Thanks for taking it.

Related Posts

Angular Material Table

Angular Material Example

Angular 8 Tutorial

Angular Material Example

Angular 8 HttpClient Example

14 Comments
  1. Gajanan says

    HI,

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

  2. Ayush Shukla says

    First of all a huge thanks to you guys specially KRUNAL, your articles are such an amazing that everyone can understand it very easily. I am learning angular through your blog.
    I have my data in MySQL database and I want to access(show) it on Angular 6 using NodeJS as an intermediary. Is it possible to access that using rest APIs. If I want to apply CRUD operations, how can I do that.
    If there is any link please give me that else make an article covering this problem. Means how our data in database can be displayed on angular, we can add/delete data to database by adding /deleting through angular and vice-versa.

    Thanks in Advance
    Ayush

  3. Ashraf says

    Thanks for this tutorials.

  4. mohamed abbullah says

    i want to contribute to this good article .
    there is 2 error can face any one who will read this article in angular 6 :
    you may facing error with ng2-completer > install it via
    npm cache clean –force
    npm i ng2-completer –save

  5. Abhijith says

    Hi,
    i have done the same program but i am getting an error as follow

    “ERROR Error: Cannot find a differ supporting object ‘Response with status: 200 OK for URL: http://localhost:4000/characters‘ of type ‘object’. NgFor only supports binding to Iterables such as Arrays.”

    can you please find me a solution

  6. Thilini Weerasinghe says

    That was amazing.I like that very much . But I couldn’t get the data for my table . can you please help me.

  7. YASSINE ZELLAMA says

    Hello,

    Can someone pls send me the final file, i did not succeed in making the table

  8. Umesh says

    how we can add column header dynamically in that table ?

  9. Umesh says

    dynamically column header adding ?

  10. fatemeh Maleki says

    Can I show a total of my rows in the footer of the table?

  11. Ram Naresh says

    I am not able to see the smart table

  12. Karuppasamy says

    How can I do, Create, Edit, Delete actions, update to API

  13. kartik pandey says

    ts
    this.userService.List().subscribe((data: user[]) => {
    this.totalRows = data.length;
    this.list=data;
    });

    html

    Total rows: {{ totalRows }}

  14. kapil says

    how can I update delete database

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.