How to create an Angular table in Angular 11|12 ?

HTML tables allow web designers and developers to arrange data into rows and columns. Based on different UI for Angulars like Angular material, ng-bootstrap, and other UI, we can create an angular table in different ways. We’ll demonstrate and create an angular table example in two ways.

In this articles, we’ll explore and learn how to create angular data table in Angular 11 using regular HTML table element and Angular material table. Let’s get started.

Some of best Angular table libraries

There are plenty of third parties libraries for making Angular tables. These libraries provide extra and advanced features which we will not get from normal HTML tables. These advanced features include sorting, pagination, responsiveness, and filtering features. Here I have listed some popular Angular table libraries.

Libraries NamePros Notes
Angular material tablesIs one of the most popular libraries that provide material design UI for our angular project. The angular material table is a component of the material library and provides all the table features we needed for our project as we discussed earlier.The deep learning curve and, if you are using material design for your UI, then is ok. The size of the libraries package is 11.3MB if you are using these libraries only for tables, then is big.
Bootstrap tableIs also one of most popular UI design for an angular project like material design and have all tables features you needed. The size of libraries is 3.87 MB.
ngx-datatableHave all tables features and is good for presenting large and complex data.This library is not updated for the last four years.
@swimlane/ngx-datatable
Have all tables features and is good for presenting large and complex data. Built specifically for Angular tables.The size of libraries is 3.98 MB.
primeng tablePrimeNG is a collection of rich UI components for Angular and is open source. Have all features need for an angular table.The size of libraries is 24.4 MB.
ag-grid-angularAG Grid is a fully-featured and highly customizable JavaScript data grid. No third-party dependencies.The size of libraries is 1.6 MB.
Angular tables libraries

Prerequisites:
To create and run an Angular project, We need nodejs and Angular CLI already install in our system, if not then check how to install nodejs and angular in Ubuntu. Angular CLI allows us to create an Angular project, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. To install the Angular CLI, open a terminal and run the following command:

npm install -g @angular/cli

Setting up a project for angular table Apps

Let create our angular project for angular table apps, name the project angularTables. We need to create and add two components, one for example of regular HTML and the other for an Angular material.

ng start angularTables
ng generate component regular-table
ng generate component material

In our app.component.html file, we have two buttons to route to our two components. Edit app.component.html file.

<div class="example-button-row">
    <button mat-button color="success" routerLink="/regular-table">HTML Table</button>
    <button mat-button color="success" routerLink="/material">Material Table</button>
</div>
<router-outlet></router-outlet>

We need dummy data, we’ll first create dummy students data so that we can use it in our angular table example. Create a folder called data in the assets folder and add a file called students.json inside the data folder.

[
    {
        "name": "Will Smith",
        "gender": "Male",
        "country": "USA"
    },
    {
        "name": "Jackline Joy",
        "gender": "Female",
        "country": "Sri Lanak"
    },
    {
        "name": "Alu Arjun",
        "gender": "Male",
        "country": "India"
    },
    {
        "name": "Kavitha Kumar",
        "gender": "Female",
        "country": "India"
    },
    {
        "name": "John Snow",
        "gender": "Male",
        "country": "United Kingdom"
    },
    {
        "name": "Priya kanana",
        "gender": "Female",
        "country": "India"
    },
    {
        "name": "Shri Devi",
        "gender": "Female",
        "country": "Sri Lanka"
    },
    {
        "name": "Richard Roy",
        "gender": "Male",
        "country": "France"
    },
    {
        "name": "Sonu Nigam",
        "gender": "Male",
        "country": "India"
    },
    {
        "name": "Priya Dutt",
        "gender": "Female",
        "country": "USA"
    }
]

Example of the Angular table using regular HTML Table

If you are not using any UI library, then the regular HTML table is enough to display and arrange data in rows and columns. With table tag, we can define HTML table, tr tag for table row, th to define a table heading cell and each table data/cell is defined with a td tag.

angular table example

We need to fetch data first from the source, the source can be a server or local static data. Angular 4.3 introduces an Angular httpClient module to request a call to the HTTP request. In this example, we are using fetch API. The Fetch API is a newer built-in feature of JavaScript that makes working with requests and responses easier. Edit regular-table.component.ts to fetch our dummy data.

import { Component, OnInit } from '@angular/core';

export interface IStudent {
  name: string;
  gender: string;
  country: string;
}

@Component({
  selector: 'app-regular-table',
  templateUrl: './regular-table.component.html',
  styleUrls: ['./regular-table.component.scss']
})
export class RegularTableComponent implements OnInit {
  students: IStudent[];

  ngOnInit(): void {
    fetch('./assets/data/students.json').then(res => res.json())
      .then(json => {
        this.students = json;
      });
  }
}

Once we have our data in hand, we can display data in our component template. Edit regular-table.component.html file to display data in tables.

<div style="margin:0 30px;">
    <h2 style="text-align: center;">Regular HTML Table</h2>
    <table>
        <tr>
            <th>S.no</th>
            <th>Name</th>
            <th>Gender</th>
            <th>Country</th>
        </tr>
        <tr *ngFor="let student of students; index as i">
            <td>{{ i }}</td>
            <td>{{ student.name }}</td>
            <td>{{ student.gender }}</td>
            <td>{{ student.country }}</td>
        </tr>
    </table>
</div>

We have applied style in our table, for the table header row, we have a red background and all even rows have a grey background. Let add style for our angular table in regular-table.component.scss file.

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
  }
  
  th {
    background-color: red;
    border: 1px solid red;
  }
  td {
    border: 1px solid #dddddd;
  }
  td, th {
    text-align: left;
    padding: 8px;
  }
  
  tr:nth-child(even) {
    background-color: #dddddd;
  }

Angular table example using Angular material

If you’re using Angular material UI for your project, then it’s the best choice to use an Angular material table to display our data in rows and columns.

Install and configure angular material in our project

To use the angular material table we need to add Angular Material to our project. Use the Angular CLI’s install schematic to set up your Angular Material project by running the following command:

ng add @angular/material
angular material table example

We have to import the angular material table and button in our app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MatButtonModule } from '@angular/material/button';
import { MatTableModule } from '@angular/material/table';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RegularTableComponent } from './regular-table/regular-table.component';
import { MaterialComponent } from './materail/materail.component';

@NgModule({
  declarations: [
    AppComponent,
    RegularTableComponent,
    MaterialComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MatButtonModule,
    MatTableModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Angular material allows us to create a responsive table that is fully compatible with PC, tablets, and mobile devices. For data for the table, we are using the same students’ dummy data. Let edit the material.component.ts file to retrieve data from our source, in real project data can be from the server, but in our case is from static JSON data.

import { Component, OnInit } from '@angular/core';

export interface IStudent {
  name: string;
  gender: string;
  country: string;
}

@Component({
  selector: 'app-materail',
  templateUrl: './materail.component.html',
  styleUrls: ['./materail.component.scss']
})
export class MaterailComponent implements OnInit {
  displayedColumns = ['SNo', 'name', 'gender', 'country'];
  dataSource: IStudent[];

  ngOnInit(): void {
    fetch('./assets/data/students.json').then(res => res.json())
      .then(json => {
        this.dataSource = json;
      });
  }
}

Once we have our data in hand, we can display data in our material component template. Edit material.component.html file to display data in tables.

<div style="margin:0 30px;">
    <h2 style="text-align: center; color:blueviolet;">Angular material table</h2>
    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
        <!--- Note that these columns can be defined in any order.
              The actual rendered columns are set as a property on the row definition" -->

        <ng-container matColumnDef="SNo">
            <th mat-header-cell *matHeaderCellDef> S.no </th>
            <td mat-cell *matCellDef="let element; let i = index;">{{ i }}</td>
        </ng-container>

        <!-- Name Column -->
        <ng-container matColumnDef="name">
            <th mat-header-cell *matHeaderCellDef> Name </th>
            <td mat-cell *matCellDef="let element"> {{ element.name }} </td>
        </ng-container>

        <!-- Weight Column -->
        <ng-container matColumnDef="gender">
            <th mat-header-cell *matHeaderCellDef> Gender</th>
            <td mat-cell *matCellDef="let element"> {{ element.gender }} </td>
        </ng-container>

        <!-- Symbol Column -->
        <ng-container matColumnDef="country">
            <th mat-header-cell *matHeaderCellDef> Country </th>
            <td mat-cell *matCellDef="let element"> {{ element.country }} </td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns; let i = index"></tr>
    </table>
</div>

Edit material.component.scss to make table width full and apply a background to table header using style.

table.mat-table {
    display: table;
    width: 100%;
    th {
        background-color: red;
        color: white;
    }
}

Angular bootstrap table

Angular Bootstrap table component is responsive tables that allow us to filter, pagination, and table can have nice UI by using bootstrap style class name. In our previous example, we have a complete example on the Angular bootstrap table with filter and pagination. Check here our example on it.

Conclusion
In this tutorial, we have demonstrated two ways to create an Angular table using a regular HTLM table and an Angular material table.

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top