Saturday, March 14, 2020

Build Dynamic HTML Table in Angular 9/8 with ngFor

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

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
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
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;
    }) 
  }
}

Displaying Data in Angular HTML Table using ngFor

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.

No comments:

Post a Comment