Menu Close

JsonPipe use in Angular

In this article we will learn about JsonPipe use in Angular. Sometimes we want to show the json representation of the object. This pipe is exactly for that. Look at the following files and output of this json pipe. So, we can output the person object in a json format with json pipe. Please read my previous article How to pass parameters to pipes in Templates.

On the below typescript we created the sample json file that we want to render in HTML.

import { DecimalPipe, UpperCasePipe } from '@angular/common';
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

  constructor() { }

  person = { firstName: 'Jhon', lastName: 'Smith',
             address:{ stretNumber: 'Florida', streetName: '1st street', city: 'newcity', state: 'ST', zipcode: '00000' }
           };
ngOnInit(): void {
  console.log(this.person);
}
         
}

We implement the JSON file with Pipe or Without pipe like below,

  <div class="col-sm-8">
    <h5>Without JsonPipe:</h5>
    <p>{{person}}</p>
  </div>
  <div class="col-sm-8">
    <h5>With JsonPipe:</h5>
    <p>{{person | json}}</p>
  </div>

You can see on the above without use of Json pipe it print [object object].

Conclusion

In this article we learnt about How to use pipes in Component Class. Usage of pipes in component class is a little bit different. First, we need to import pipe from Angular common library and add it to providers array of the component and then we need to inject in the constructor of the class.

Leave behind your valuable queries and suggestions in the comment section below. Also, if you think this article helps you, do not forget to share this with your developer community. Happy Coding 🙂

Related Articles

Jayant Tripathy
Coder, Blogger, YouTuber

A passionate developer keep focus on learning and working on new technology.

Leave a Reply

Your email address will not be published. Required fields are marked *