How to Create Dynamic Angular 11 HTML Table using ngFor Directive

Throughout this quick and straightforward tutorial, you will learn how to create a dynamic HTML table in an Angular app using the ngFor directive from starting to end.

Before starting this angular HTML tutorial, i would like to tell you more about angular *ngFor directive. The ngFor directive helps repeat the element for every item of an ordered or unordered list. Moreover, every element generated by the *ngFor loop directive gets the specific index number; in this tutorial, you will learn to build a dynamic HTML table with the *ngFor directive.

Setting Up Environment

To get along with this example, you need to configure the latest angular CLI in your system:

npm install -g @angular/[email protected]

Using the following command creates a new project; ignore the step if already done:

ng new angular-dynamic-html-table-example

Angular 11 HTML Table with *ngFor Example

We have ascertained what is ngFor and why it is used in an angular. Furthermore, to create and display data dynamically in Angular HTML table, you will be doing two things respectively:

Fetch Data using Angular Service

To display data in the HTML table, you need to make an HTTP request using REST API; you need to create an angular service. In the service file, all the code will be conjugated for making HTTP GET request.

You need to import HttpClientModule and register in imports array within the 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 { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Next, open and update the table.service.ts file, this immaculate service helps you make HTTP request to get data using REST API:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class TableService {

  private REST_API = "https://jsonplaceholder.typicode.com/users";

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }

  constructor(private httpClient: HttpClient) { }

  fetchUsers(): Observable<any[]> {
    return this.httpClient.get<any[]>(this.REST_API);
  }

}

Show Dynamic Data in Angular Table

Head over to app.component.ts and import TableSerivce, define the array variable, inject service in constructor most importantly, make the request by accessing the fetchUsers() method within the ngOnInit lifecycle hook:

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

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

export class AppComponent {
   
  Users = [];

  constructor(private tableService: TableService) { }

  ngOnInit() {
    this.tableService.fetchUsers().subscribe((response: any[])=>{
      this.Users= response;
    })  
  }

}

Subsequently, open and update the code in app.component.html file:

<h2>Angular HTML Table Demo</h2>

<table>
  <thead>
    <tr>
      <th>#ID</th>
      <th>Name</th>
      <th>Email</th>
      <th>Phone</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of Users">
      <th>{{ user.id }}</th>
      <td>{{ user.name }}</td>
      <td>{{ user.email }}</td>
      <td>{{ user.phone}}</td>
    </tr>
  </tbody>
</table>

Start the angular development server:

ng serve --open

In the above example, you have learned to create a dynamic HTML dynamic table in Angular. Also, we showed you how to use ngFor directive and iterate over table row to display data dynamically using Angular service with the REST API’s help.