How to Print an Object in Angular?

Objects are real-world entities that contain data in the form of key-value pairs and we are most of the time dealing with these objects while building our application.

While working with these objects, we commonly face a problem, where we want to print the whole object or its key-value pairs in the template(html) file, but all we get is errors.

For example, if you try to print the whole object, you will get a string [object Object] as a result instead of printing the actual object.

Problem with directly printing an object in Angular

How can you solve this problem?

Well, if you want to print an object in your component’s template file, you can use Angular’s json pipe. The json pipe converts a given value into a JSON-formatted string which can be directly printed in the component’s template.

For demonstration purpose, I have created an Angular app which has a component home.component.ts. Inside the home component, we have an object myObj:

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {

  // Declare an object
  myObj = {
    name: 'John Doe',
    age: 25,
    address:{
      city: 'New York',
      country: 'USA'
    }
  };
  
  constructor() { }

  ngOnInit(): void { }
  
}

We want to directly print the object myObj in our template file. To accomplish that we can apply the json pipe on this object in our template file:

<p>The Object is:</p>
<div>
    {{ myObj | json }}    <!-- Print the object -->
</div>

Below is the outcome of the above code:

Print an object in Angular using json pipe

As you can see from the above output, the object is printed as it was in the ts file.


Printing the Keys and Values of an Object

If you have an object and you want to print all of its keys and values one by one in the template file, you can use the *ngFor loop directive with the keyvalue pipe.

The keyvalue pipe is released in Angular 6.1 and it can be used to loop through objects and maps. It transforms the given object or map into an array of key-value pairs which can be directly traversed using the *ngFor loop directive.

Let’s say we have an object myObj in our ts file which contains the information of a person:

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {

  // Declare an object
  myObj = {
    name: 'John Doe',
    age: 25,
    city: 'New York',
    country: 'USA'
    
  };
  
  constructor() { }

  ngOnInit(): void { }
  
}

We want to print the keys and values of this given object as list items inside our template file.

To accomplish that we can apply the keyvalue pipe to the given object inside the *ngFor loop:

<div>
    <p>The object's keys and values are as follows:</p>
    <ul>
        <li *ngFor="let item of myObj | keyvalue">
            {{ item.key }} - {{ item.value }}
        </li>
    </ul>
</div>  

Here is the output of the above code:

Print keys and values of an object using keyvalue pipe

As you can see from the above output, the *ngFor loop runs over all the keys and values of the object and print them one by one.

But are they printed in the original order? No, right. Let’s see next how we can fix this problem.


Print the Keys and Values of an Object in the Original Order

When you iterate over an object using the keyvalue pipe, it prints the object’s items in the ascending order of their keys. This is actually the default behavior of the keyvalue pipe.

So, if you want to print the object’s items in the original order, or want to sort them in descending order of the keys or in some other custom order, you have to provide a custom compare function to the keyvalue pipe.

Let’s say we want to print the object’s items in the original order using the keyvalue pipe. To accomplish that we have to define a custom comparer function in our ts file. This function will maintain the original order of the object’s items.

import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {

  // Declare an object
  myObj = {
    name: 'John Doe',
    age: 25,
    city: 'New York',
    country: 'USA'
    
  };
  
  constructor() { }

  ngOnInit(): void { }

  // Define the comparer function
  keepOriginalOrder(a:any, b:any){
    return a.key;
  }
  
}

Now, we need to pass this comparer function keepOriginalOrder() to the keyvalue pipe inside the *ngFor loop.

<div>
    <p>The object's keys and values are as follows:</p>
    <ul>
        <li *ngFor="let item of myObj | keyvalue:keepOriginalOrder ">
            {{ item.key }} - {{ item.value }}
        </li>
    </ul>
</div>  

Here is the output:

Print keys and values in original order with keyvalue pipe

As you can see from the above image, the keys and values of the object are printed in the same order as they are in the ts file.


Conclusion

In this article, we learned how we can print an object in the template file of our component using Angular.

To print an object in the template of our component, we can use Angular’s json pipe. The json pipe converts the given value into the JSON formatted string.

If you also want to print the keys and value of the object, you can apply the keyvalue pipe inside the *ngFor loop directive.

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts