Read an External JSON file in Angular 4 and Convert Data to HTML Table

You can use the HttpClient service in Angular 4 to read and extract data from an external JSON file. Using the Get() method of HttpClient class, you can easily open and read data from a JSON file. Here in this post, I am sharing a simple example on how to read JSON data from a file and convert the data to an HTML table.

Read JSON Data from File and Bind it to an HTML Table in Angular 4

JSON or JavaScript Object Notation, as you know is a data format that allows you to conveniently store and share data using any medium. JSON is language independent and can be easily bind with any kind of application. You can use JSON data in your Angular 4 applications.

Related: How to Bind JSON array or data to an HTML table in AngularJS using ng-repeat

The JSON Data

Here’s a sample data in JSON format. I have saved the data in a file named Birds.json.

[{
    "ID": "001",
   "Name": "Eurasian Collared-Dove",
    "Type": "Dove",
    "Scientific Name": "Streptopelia"
},
{
    "ID": "002",
    "Name": "Bald Eagle",
    "Type": "Hawk",
    "Scientific Name": "Haliaeetus leucocephalus" 
},
{
    "ID": "003",
    "Name": "Cooper's Hawk",
    "Type": "Hawk",
    "Scientific Name": "Accipiter cooperii" 
}]

Create the Angular 4 Project

I am hoping that you have already setup Angular 4 in your computer. If not, then please read this post. It will guide you with the setup procedure.

Open cmd prompt and go to the folder where you want to create your project. Type this command …

ng new json2angular

Now, go to the folder.

cd json2angular

Note: We have created a JSON file above named Birds.json. Save the file inside the assets folder. Here’s the path.

/src/assets/birds.json

Import HttpClientModule to the Project

First, open app.module.ts file under src/app/ folder and add HttpClientModule.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/https';

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

Next, we’ll create our component, where we’ll add or import HttpClient service. Adding this service to our project will ensure that we have access to the Get() method and its properties, which we need to access files in the server and read its contents.

Open app.component.ts file and add the below code.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/https';
import { HttpErrorResponse } from '@angular/common/https';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'JSON to Table Example';
  constructor (private httpService: HttpClient) { }
  arrBirds: string [];

  ngOnInit () {
    this.httpService.get('./assets/birds.json').subscribe(
      data => {
        this.arrBirds = data as string [];	 // FILL THE ARRAY WITH DATA.
        //  console.log(this.arrBirds[1]);
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );
  }
}

I have declared an array named arrBirds of type string. I am adding the JSON data extracted from the file into an array, which I’ll later bind with a <table> using *ngFor directive.

You can now launch the server, ng server --o, to check if there are no errors. Please make sure that you have saved the JSON file Birds.json in the assests folder in your project, else it will throw an error.

Now let’s create our application template. Its where we’ll add the HTML <table> element and bind the array to the table.

Open app.commonent.html file and copy and paste the below markup to the file.

<div style="text-align:left;width:500px;">
    <h1>
        {{ title }}!
    </h1>

    <table *ngIf="arrBirds">
        <!-- ADD HEADERS -->
        <tr>
            <th>ID</th>
                <th>Name of Bird</th>
                    <th>Type of Bird</th>
        </tr>

        <!-- BIND ARRAY TO TABLE -->
        <tr *ngFor="let bird of arrBirds">
            <td>{{bird.ID}}</td>
                <td>{{bird.Name}}</td>
                    <td>{{bird.Type}}</td>
        </tr>
    </table>
</div>

Save the file. Go the browser to check the output. If you want you can style the <table> and its contents.

You can add in-line style to your table or add few classes in your app.component.css file.

table, th, td 
{
    margin: 10px 0;
    border: solid 1px #333;
    padding: 2px 4px;
    font: 15px Verdana;
}
th {
    font-weight:bold;
}

That’s how you convert JSON data to an HTML table in Angular 4. Now you know how simple it is.

I am using Angular 4 HttpClient service in my example, so I can have access to the Get() method, using which I can access any file in the server, read the file and populate the data in an Array. I am then binding the array to an HTML <table> element (you can bind it with other elements like the SELECT element and view it.

Thanks for reading.

Previous - Get File Info like Size, Name and Type from Multiple File Input in Angular 4Next - How to Create a Bar Chart in Angular 4 using Chart.js and ng2-charts



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!