Friday, January 10, 2020

Build Dynamic HTML Table in Angular 9/8 with ngFor

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
 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;
    }) 
  }
}
Displaying Data in Angular HTML Table using ngFor
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>
Build Dynamic HTML Table in Angular 9/8 with ngFor