Angular json as html

Angular 14 Display JSON Data in Table Tutorial

To display JSON data in HTML table using angular 14; Through this tutorial, you will learn how to read json file and display JSON file data into the HMTL table in angular 14 apps. And as well as show you how to use the bootstrap library with HTML table.

How to Display JSON File Data Into HTML Table in Angular 14

  • Step 1 – Create New Angular App
  • Step 2 – Install & Setup Bootstrap Package
  • Step 3 – Create JSON Data File
  • Step 4 – Update app.Component ts File
  • Step 5 – Create HTML Table and Display List From Json
  • Step 6 – Define Required Modules in tsconfig.json
  • Step 7 – Start the Angular App
Читайте также:  Python использовать значение переменной

Step 1 – Create New Angular App

First of all, open your terminal and execute the following command on it to install angular app:

Step 2 – Install & Setup Bootstrap Package

Execute command to install the latest version of Bootstrap in angular apps:

npm install bootstrap --save

Then, add the Bootstrap CSS path in angular.json file to enable the styling:

"styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.scss" ]

Step 3 – Create JSON Data File

Create json file; so visit src/app directory and create users.json file. Then add the following code into it:

[< "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "[email protected]" >, < "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "[email protected]" >, < "id": 3, "name": "Clementine Bauch", "username": "Samantha", "email": "[email protected]" >, < "id": 4, "name": "Patricia Lebsack", "username": "Karianne", "email": "[email protected]" >, < "id": 5, "name": "Chelsey Dietrich", "username": "Kamren", "email": "[email protected]" >, < "id": 6, "name": "Mrs. Dennis Schulist", "username": "Leopoldo_Corkery", "email": "[email protected]" >, < "id": 7, "name": "Kurtis Weissnat", "username": "Elwyn.Skiles", "email": "[email protected]" >, < "id": 8, "name": "Nicholas Runolfsdottir V", "username": "Maxime_Nienow", "email": "[email protected]" >, < "id": 9, "name": "Glenna Reichert", "username": "Delphine", "email": "[email protected]" >, < "id": 10, "name": "Clementina DuBuque", "username": "Moriah.Stanton", "email": "[email protected]" > ]

Step 4 – Update app.Component ts File

Update app.component.ts file; so visit src/app directory and open app.component.ts. Then add the following code into component.ts file:

import < Component >from '@angular/core'; import UsersJson from './users.json'; interface USERS < id: Number; name: String; username: String; email: String; >@Component(< selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] >) export class AppComponent < Users: USERS[] = UsersJson; constructor()< console.log(this.Users); >>

Step 5 – Create HTML Table and Display List From Json

Create table in html to display json file data into it; So, visit src/app/ directory and open app.component.html and update the following code into it:

 

Angular Display Data from Json File Example

Id Name Username Email
> > > >

Step 6 – Define Required Modules in tsconfig.json

Define the resolveJsonModule and esModuleInterop inside the compilerOptions object; as shown below:

Читайте также:  Teremoc ru index php

Step 7 – Start the Angular App

Execute the following command on the terminal to start angular app:

Open the browser and type the given url then hit enter to run the app:

Conclusion

Display json data in HTML table using angular 14; In this tutorial, you have learned how to fetch data from JSON file and display data in a table.

Источник

How to Use JSON in Angular

How to use JSON in Angular using a REST API and local files.

Nicolas Lule Web Developer in Chicago, IL

How to use JSON in Angular

In this article, I’ll explain how to use JSON in an Angular web application using two different approaches. Let’s start.

Setup the Angular application

Create a new Angular application:

Open the project in your favorite code editor and navigate to src/app/app.component.html and replace everything with just the following line of code:

Run your local server with ng serve and navigate to http://localhost:4200, you should see something like this:

Angular test app image

Now, with our app all set up, let’s explore the two different methods to use JSON in Angular.

Method #1: JSON in Angular with a TypeScript Module

Since Typescript 2.9, we can import JSON files as regular Typescript modules by simply enabling it in our tsconfig.json file.

Open tsconfig.spec.json and add “resolveJsonModule”: true, as shown below:

 /* To learn more about this file see: https://angular.io/config/tsconfig. */ < "extends": "./tsconfig.base.json", "compilerOptions": < "outDir": "./out-tsc/spec", "resolveJsonModule": true, "types": [ "jasmine" ] >, "files": [ "src/test.ts", "src/polyfills.ts" ], "include": [ "src/**/*.spec.ts", "src/**/*.d.ts" ] > 

We now need a JSON file to start reading the data. Create a new file called sample.json in the src/app/ folder and paste the following product JSON data:

Next, we need to import the JSON data to our app component by adding import * as data from ‘./sample.json’; in the top import section in our app.component.ts file.

Now the app component has access to our JSON file but we still need to read the data. Let’s define and assign the JSON data to a variable in our class component: products: any = (data as any).default; .

Your app.component.ts file should look similar to this:

 import < Component >from '@angular/core'; import * as data from './sample.json'; @Component(< selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] >) export class AppComponent

Finally, we need to display our data in our template. Open up app.component.html and add the following unordered list:

Here, we are just iterating through the name values of our product data with *ngFor and displaying each value in a list.

Run your server and go to http://localhost:4200. You should see something like this:

Angular app with a JSON example

Method #2: JSON in Angular with an HTTP Request

If you are trying to use JSON through an HTPP request with your web application, Angular provides a client HTTP API, which provides some excellent features.

To use it, we first need to import the HTTPClientModule in our app. Open app/app.module.ts and add two lines of code, as shown below.

 import < BrowserModule >from '@angular/platform-browser'; import < NgModule >from '@angular/core'; import < HttpClientModule >from '@angular/common/http'; import < AppComponent >from './app.component'; @NgModule(< declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] >) export class AppModule

Next, open app.component.ts , and let’s add some code. First, we need to import the HTPPClient module at the top:

 import < HttpClient >from '@angular/common/http'; 

After importing the HTTPclient module in our component, we can either use a local JSON file or a REST API. We’ll cover both next.

Using a REST API

We will be using a free service called JSONPlaceholder to retrieve JSON data and test our code. We can create a function to make a GET request to retrieve users data by adding the following code:

 constructor(public httpClient: HttpClient)<> giveMeData()< this.httpClient.get('https://jsonplaceholder.typicode.com/users').subscribe((resp)=>< this.var1 = resp; >); > 

Your final app.component.ts file should look like this:

 import < Component >from '@angular/core'; import < HttpClient >from '@angular/common/http'; @Component(< selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] >) export class AppComponent < title = 'test-app'; constructor(public httpClient: HttpClient)<>giveMeData()< this.httpClient.get('https://jsonplaceholder.typicode.com/users').subscribe((resp)=>< this.var1 = resp; >); > > 

Finally, let’s display our data in our app.component.html template by adding a button to retrieve the names in a list.

Run your server with ng serve and you should get:

JSON data with GET request

Using a local JSON file

We can also use a local JSON file by uploading it to our src/assets/ folder and modify our giveMeData() function as follows:

 import < Component >from '@angular/core'; import < HttpClient >from '@angular/common/http'; @Component(< selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] >) export class AppComponent < title = 'test-app'; constructor(public httpClient: HttpClient)<>giveMeData()< this.httpClient.get('assets/sample.json').subscribe((resp)=>< this.var1 = resp; >); > > 

And there you have it! A couple of methods to use JSON in an Angular web app. Happy coding!

Источник

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

www.encodedna.com

You can use the HttpClient service in Angular 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

Hi there, Angular 15 was resently released with some cool new features. I would recommend upgrading to the current version. In Angular 15, you can use two simple methods to read data from JSON file and convert the data into a table. The process is slightly different and its worth exploring.

How to read data from a local JSON file in Angular 15 and convert data to an HTML table

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 applications.

The JSON Data

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

After you create file, you’ll have to save the file inside the assets folder in your angular project. Here’s the path.

But first, create the project.

Create the Angular Project

I am hoping that you have already setup Angular 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 …

Note: Don’t forget to save the JSON file in the assets folder inside your angular project.

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

Now, let’s understand what the above code is doing.

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 &lttable> using *ngFor directive.

You can now launch the server, ng serve —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 &lttable> 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> >! </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>></td> <td>></td> <td>></td> </tr> </table> </div>

Save the file. Go to the browser to check the output. If you want you can some CSS style to the table and its content.

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

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

🚀 Now, you can also do this easily and more efficiently in Angular’s lastest version, using two different methods. Check this out.

I am using Angular 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 &lttable> element (you can bind it with other elements like the SELECT element and view it.

Источник

Оцените статью