Working with data in Angular 8, part 2

Displaying the contents of nested objects

By: Ajdin Imsirovic 06 September 2019

This post is the second post in the “Working with data in Angular” series. The first post can be found here.

You can find the completed example app for this article on Stackblitz.

We start our commits with the initial starter Angular 8 app as can be found when you first start Stackblitz.

Preparing our app

A looping staircase Photo by Tine Ivanič, @tine999 on Unsplash

We’ll kick things off by removing all traces of the hello component from the initial commit, and we’ll update our app.component.ts so that it holds a more complex data structure called frontends, as follows:

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
28
29
30
31
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  frontends = [
    {
      name: 'Angular',
      details: {
        type: 'framework',
        versions: {
          current: 8,
          previous: 7
        } 
      }
    },
    {
      name: 'React',
      details: {
        type: 'library',
        versions: {
          current: 16.9,
          previous: 16.8
        } 
      }
    }
  ];
}

We have an object that contains some properties and some other nested objects inside.

The commit at this point is titled Added the data object inside app.component.ts.

Looping over nested objects in Angular 8

Let’s now try showing some data from our app component’s class file, in our app component’s HTML template:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<h1>Frontends:</h1>
<table>
  <tr>
    <th>#</th>
    <th>Name</th>
    <th>Type</th>
    <th>Current Version</th>
  </tr>
  <tr *ngFor="let f of frontends; let i = index ">
    <td>{{ i + 1 }}</td>
    <td>{{ f.name }}</td>
    <td>{{ f.details.type }}</td>
    <td>{{ f.details.versions.current }}</td>
  </tr>
</table>

Let’s also make our table look a bit nicer by adding the following code to app.component.css:

1
2
3
4
5
6
7
8
9
10
11
p {
  font-family: Lato;
}
table {
  border-collapse: collapse;
  font-family: Arial, sans-serif;
}
th,td {
   border: 1px solid black;
   padding: 5px;
}

We can see that this is working perfectly: Successfully displaying nested objects in Angular 8

With the let i = index we do get the count of our table rows, starting with 0. That’s why when we actually display the index, we increment it by 1, so that we actually start counting from zero instead of from 1.

To access each individual property on a nested object, we simply use the dot operator, such as this: f.details.versions.current.

The commit for this step in our example app can be found here

We’ve just learned how easy it is to loop over nested objects in Angular. We’ll soon be adding part 3 in this series!

Feel free to check out my work here: