First, install a most recent version of Angular CLI, running the following command.
Create Table Component
Run the command to create a HTML data table component.
Add the following code in your angular service file:
open the app/table.component.html file and add the following code:
npm install -g @angular/cli@latestThen, run the following command to install the Angular app.
ng new project-nameStart the app:
cd project-name
ng serve --openView your app on the following URL: localhost:4200.
Create Table Component
Run the command to create a HTML data table component.
ng g c tableRendering Table Data with Angular Service
Add the following code in your angular service file:
import { Injectable } from '@angular/core';Next, open the table.component.ts file and replace the current code with the following code.
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/');
}
}
import { Component, OnInit } from '@angular/core';Displaying Data in Angular HTML Table using ngFor
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;
})
}
}
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>