Multiple ways to Print array of objects in Angular with example?
This tutorial shows multiple ways to print the array of objects. One way is using json pipe in Angular. Another way using object property notation
For example, We have an array of objects declared in the typescript component in Angular
roles: { id: number, name: string }[] = [
{ "id": 0, "name": "admin" },
{ "id": 1, "name": "user" },
{ "id": 2, "name": "superadmin" }
];
prints the object using angular template syntax in HTML
{{roles}}
Would print a list of [object Object] in UI as seen below.
[object Object],[object Object],[object Object]
using the ngFor directive, We will print the object
<ul>
<li *ngFor="let role of roles">{{role}}</li>
</ul>
Outputs displayed on UI
[object Object]
[object Object]
[object Object]
How do you print the object to the screen or the browser to the console?
using json pipe in Angular
Angular has an inbuilt json pipe that prints beautify of json code.
In Html code, json pipe is used as below.
{{roles|json}}
And prints json
[
{ id: 0, name: "admin" },
{ id: 1, name: "user" },
{ id: 2, name: "superadmin" },
];
Another way is to iterate with ngFor and print an object
<ul>
<li *ngFor="let role of roles">{{role |json}}</li>
</ul>
Print an array of objects using object notation
In Javascript, Object values can be retrieved using two syntaxes.
- using object dot notation syntax. property is accessed using dot notation syntax as given below Syntax
object.property;
Here is an example code
<ul>
<li *ngFor="let role of roles">{{role .id}}- {{role.name}}</li>
</ul>
- using a key with object square brackets
In this values from the object are retrieved by passing the key to square brackets.
syntax:
object["key"];
Here is an example code
<ul>
<li *ngFor="let role of roles">{{role["id"]}}- {{role["name"]}}</li>
</ul>
In both above cases, Output as shown below
0 - admin;
1 - user;
2 - superadmin;
using JSON.stringify in component to print array objects
Created a getter. An array of objects are deserialized using JSON.stringify in the typescript component.
get printroles() { return JSON.stringify(this.roles) };
Call the getter inside an HTML component.
{{printroles}}