Angular Smart table is a module to easily display data in a table with a set of inbuilt features such as filtering, sorting, etc., in a declarative way. The smart table in Angular has the following focus points:
lightweight:
The 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:
The smart-table is widely tested, making the module stable, modular, and extensible: The core features can be accessed with the controller API, 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 module’s design has been thought carefully, and it is straightforward to get into the source code to modify/customize the module to fit your needs best.
In this Angular Smart Table Example, we use the ng2-smart-table library for this example. The ng2-smart-table library provides us with sorting, searching, and filtering functionalities. So let us start with this example.
Angular Smart Table
Angular 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, making the module stable, modular, and extensible: The core features can be accessed with the controller API 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 of carefully, and it is straightforward to get into the source code to modify/customize the module to fit your needs best.
First, we start our tutorial by installing Angular CLI. If you have already installed it, then you can skip the installation.
Step 1: Install the Angular project.
npm install -g @angular/cli
If it does not install, then try in the administrator mode.
After that, create a new Angular 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
One change in the latest Angular now depends on the latest TypeScript and RxJS versions. So, if you install third-party packages right now, it is not compatible with Angular.
In the future, all third-party libraries might upgrade their packages, but it is not compatible with Angular.
So, to fill the gap between Angular 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 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 the 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
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, which already has 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 that tells the Angular application 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.
Step 6: Configure the Angular Smart Table.
Now, create the settings object inside the 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 are only concerned about the column’s keys, which are the id, name, and age. It is the same as the Table.ts properties.
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.
- settings
- source
The settings are our columns, and the 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/
In that table, now you can search and sort based on columns.
We can do many advanced things on this table, but we will see them in the upcoming tutorials.
That’s it for this tutorial.
HI,
I am getting below error
Error: The selector “app-root” did not match any elements
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
Thanks for this tutorials.
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
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
That was amazing.I like that very much . But I couldn’t get the data for my table . can you please help me.
Hello,
Can someone pls send me the final file, i did not succeed in making the table
how we can add column header dynamically in that table ?
dynamically column header adding ?
Can I show a total of my rows in the footer of the table?
I am not able to see the smart table
How can I do, Create, Edit, Delete actions, update to API
ts
this.userService.List().subscribe((data: user[]) => {
this.totalRows = data.length;
this.list=data;
});
html
Total rows: {{ totalRows }}
how can I update delete database
Hi,
Tried to follow your blog but I am getting following error:
“ERROR in The target entry-point “ng2-smart-table” has missing dependencies:
– @akveo/ng2-completer”
I am using latest angular version.
Hi @Shirish,
you should add this dependecies to fix the issue:
“` npm install @akveo/ng2-completer –save-dev “`