The below example show how we can use JSON data in angular Application.
Example
The following command uses the Angular CLI to create a Angular application. The application name in the following example is jsoninangular.
ng new jsoninangular
Suppose we have a JSON as following:
[{
"id": 1,
"name": "Rohatash",
"email": "Roh@gmail.com"
},
{
"id": 2,
"name": "Gaurav",
"email": "Gau@gmail.com"
},
{
"id": 3,
"name": "Rahul",
"email": "rah@gmail.com"
},
{
"id": 2,
"name": "Ravindar",
"email": "rav@gmail.com"
},
{
"id": 2,
"name": "Ritesh",
"email": "rit@gmail.com@melissa.tv"
},
]
The below code use the above json on app.component.ts page.
import { Component } from '@angular/core';
interface employee {
id: Number;
name: String;
email: String;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
employeeJson=[{
"id": 1,
"name": "Rohatash",
"email": "Roh@gmail.com"
},
{
"id": 2,
"name": "Gaurav",
"email": "Gau@gmail.com"
},
{
"id": 3,
"name": "Rahul",
"email": "rah@gmail.com"
},
{
"id": 2,
"name": "Ravindar",
"email": "rav@gmail.com"
},
{
"id": 2,
"name": "Ritesh",
"email": "rit@gmail.com@melissa.tv"
},
]
Users: employee[] = this.employeeJson;
constructor(){
console.log(this.Users);
}
}
Now add the following Code on app.component.html page
<div class="container mt-5">
<h2>Angular Display Data from Json Example</h2>
<table class="table table-striped" border="1">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of Users">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
</tr>
</tbody>
</table>
</div>
<router-outlet></router-outlet>
Now run the code on browser. The following output will show:
Output