Build Dynamic HTML Table in Angular 9/8 with ngFor

Last updated on by Digamber
In this tutorial, we are going to learn how to build a dynamic HTML Table with Angular 9/8 using ngFor directive.

This tutorial contains two steps:

  • Rendering Table Data with angular service.
  • Displaying Data in the Angular HTML data table.

We need to set up an Angular project using Angular CLI.

First, install a most recent version of Angular CLI, running the following command.

npm install -g @angular/cli@latest

Then, run the following command to install the Angular app.

ng new project-name

cd project-name

Start the app:

ng serve --open

View your app on the following URL: localhost:4200.

Create Table Component

Run the command to create a HTML data table component.

ng g c table

Rendering Table Data with Angular Service

Here, we are about to create an Angular service that can be created using the HttpClient service.

Before you get started, open the app.module.ts file and import HttpClientModule in your main angular app module.

It will let you use HttpClient API to make the HTTP requests.

Next, Add the following code in your angular service file:

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

@Injectable({
  providedIn: 'root'
})

export class RestAPIService {

  private api = "https://your_api_url.com";
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }

  constructor(private httpClient: HttpClient) { }

  getData(): Observable<any[]> {
    return this.httpClient.get<any[]>(this.api+ '/users/');
  }

}

Next, open the table.component.ts file and replace the current code with the following code.

import { Component, OnInit } from '@angular/core';
import { RestApiService } from '../restapi.service';

@Component({
  selector: 'table-root',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.css']
})

export class TableComponent implements OnInit {

  ItemsArray= [];

  constructor(private restApiService: RestApiService) { }

  ngOnInit() {
    this.restApiService.get().subscribe((res: any[])=>{
      this.ItemsArray= res;
    })  
  }

}

We injected the RestAPIService in the TableComponent. In this file, we will be displaying the data.

Displaying Data in Angular HTML Table using ngFor

A table is an arrangement of data in rows and columns, or possibly in a more complex structure.

HTML data table is pretty easy to create it is created using table tag.

Every single table row is defined with the tr tag. A table header is created with the th tag. By default, table headings are set to bold and centered and a table cell is created using td tag.

Next, open the app/table.component.html file and add the following code:

<div>
   <h1>Angular HTML Table Example</h1>
   <table>
      <thead>
         <tr>
            <th>#ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Address</th>
            <th>Action</th>
         </tr>
      </thead>
      <tbody>
         <tr *ngFor="let item of ItemsArray">
            <th>{{ item.id }}</th>
            <td>{{ item.name }}</td>
            <td>{{ item.email }}</td>
            <td>{{ item.phone}}</td>
            <td>{{ item.address }}</td>
            <td>
               <button type="button" >Edit</button>
               <button type="button" >Delete</button>
            </td>
         </tr>
      </tbody>
   </table>
</div>

In the above HTML table, we assigned the ngFor directive to iterate over the data collection and display on the front-end using the HTML table component.

In the back-end, HttpClient is doing its job and fetching the data from the remote origin.

Conclusion

Finally, we have completed the Angular HTML Table tutorial with example. In this tutorial we learned how to display data dynamically using the HTML Table in Angular 9/8 using ngFor directive.

In this tutorial, we learn how to create an HTML table from scratch. However, there are other ways through which you can build a table in less time.

You can display data using the Angular Material mat-table component. The mat table directive contains the mat-cell, mat-header-cell directives to build a full scalable table to show the data to the users.

I wrote a detailed article on how to show the data with an angular material table with pagination and filtering.

You can also take the help of Bootstrap Table component to display the dynamic data in Angular.

Thanks for reading, Happy Coding!

Avatar
Digamber

Digamber Rawat is from Uttarakhand, located in northwestern part of India. He is a Full-stack developer by profession and a primary author of this blog.