Welcome folks today in this blog post we will be using the ngx-json-viewer
library to build json doc
viewer with syntax highlighting
using typescript in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
project using the below command as shown below
ng new sampleproject
cd sampleproject
And after that you need to install the below libraries
using the below command as shown below
npm i ngx-json-viewer
And after that you will see the below directory
structure of the angular app as shown below
And first of all you need to go to app.module.ts
file inside your project and copy paste the below code to include the NgxJsonViewerModule
inside the imports array as shown below
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { NgxJsonViewerModule } from 'ngx-json-viewer'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, NgxJsonViewerModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule{} |
And now we need to go to app.component.html
file and copy paste the following code
app.component.html
1 |
<ngx-json-viewer [json]="data" [depth]="3"></ngx-json-viewer> |
As you can see in the above html
code we have the json
parameter in which we are assigning the dynamic
json object which will contain the data that we need to render inside the browser. And then we have the depth
attribute for the json
viewer.
And now we need to go to app.component.ts
file and copy paste the below code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'dsf'; data = { countries:[ "India", "New Zealand", "Australia", "England", ], users:['John','Latham'], address:{ country:{ value:"India", cities:['Delhi','Chennai'], pincodes:[11,23] } } } } |
As you can see in the above typescript
code we have defined the json
object which contains various things such as nested
objects and arrays and it is highlighted as shown below.