Tips for navigating through a nested JSON object with loops

Is it possible to access the value of the Address object within an interface in Angular using *ngFor?


export  interface User {
  id: number;
  name: string;
  username: string;
  email: string;
  address: Address;
}


export interface Address {
    street: string;
    suite: string;
    city: string;
    zipcode: string;
  }

<div *ngFor="let oneuser of table">
  <p>{{oneuser.id}}</p>
  <p>{{oneuser.name}}</p>
  <p>{{oneuser.username}}</p>
  <p>{{oneuser.email}}</p>
  <p>{{oneuser.address.street}}</p>
  <p>{{oneuser.address.suite}}</p>
  <p>{{oneuser.address.city}}</p>
  <p>{{oneuser.address.zipcode}}</p>
  <hr>
</div>

Answer №1

similar to this

<div *ngFor="let oneuser of table">
<p>{{oneuser.id}}</p>
<p>{{oneuser.name}}</p>
<p>{{oneuser.username}}</p>
<p>{{oneuser.email}}</p>
<hr>
<p>{{oneuser.address.street}}</p>
<p>{{oneuser.address.suite}}</p>
<p>{{oneuser.address.city}}</p>
<p>{{oneuser.address.zipcode}}</p>

</div>

Updated

If address happens to be undefined, an error will occur in JavaScript stating that street of undefined cannot be read. You can handle this by utilizing the safe navigation operator (?.)

<div *ngFor="let oneuser of table">
<p>{{oneuser.id}}</p>
<p>{{oneuser.name}}</p>
<p>{{oneuser.username}}</p>
<p>{{oneuser.email}}</p>
<hr>
<p>{{oneuser.address?.street}}</p>
<p>{{oneuser.address?.suite}}</p>
<p>{{oneuser.address?.city}}</p>
<p>{{oneuser.address?.zipcode}}</p>

</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the basics of reading a JSON object in TypeScript

Displayed below is a basic JSON structure: { "carousel": [], "column-headers": [{ "header": "Heading", "text": "Donec sed odio dui. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id el ...

How to trigger a function in a different component using Angular 4

I have a query bar located within the header element, designed to search through a list in a separate component. How can I set up communication for the headerComponent to invoke a function in the BooksComponent? export class HeaderComponent { search ...

Making the Angular 2 Http Service Injectable

I am fetching a large object from my server using an Angular 2 service when the website loads. The structure of the data I need to fetch is as follows: { Edu: [...], Exp: [...], Links: [...], Portfolio: [...], Skills: [...] } Here&apo ...

Angular - Error: Object returned from response does not match the expected type of 'request?: HttpRequest<any>'

While working on implementing an AuthGuard in Angular, I encountered the following Error: Type 'typeof AuthServiceService' is not assignable to type '(request?: HttpRequest) => string | Promise'. Type 'typeof AuthServiceServic ...

What might be the reason why the custom markers on the HERE map are not displaying in Angular?

I'm having trouble displaying custom icons on HERE maps. Despite not receiving any errors, the icons are not showing up as expected. I have created a demo at the following link for reference: https://stackblitz.com/edit/angular-ivy-zp8fy5?file=src%2Fa ...

How can I integrate a timer into an Angular carousel feature?

I have put together a carousel based on a tutorial I found on a website. Check out the HTML code for my carousel below: <div class="row carousel" (mouseover)="mouseCheck()"> <!-- For the prev control button ...

Allowing cross-origin resource sharing (CORS) in .NET Core Web API and Angular 6

Currently, I am facing an issue with my HTTP POST request from Angular 6. The request is successfully hitting the .net core Web API endpoint, but unfortunately, I am not receiving the expected response back in Angular 6. To make matters worse, when checkin ...

Generate multiple instances of an HTML element by using ngFor and referencing an object property

In my Angular project, I am generating a unique object called starStructure based on the vote_average of each item. Here is an example of what my object array looks like: [ {"title":"Solo: A Star Wars Story", "vote_average":7.1, "starStructure":{" ...

Show the Search Results from Angular 2 in a Separate Component

When I search, the names are displayed on a suggestion list without any issues because they are not in a separate component. Search HTML <input type="text" placeholder="Search" (keyup)="getSuggestion($event.target.value)"> <div class="suggest ...

Easily implement a wide variety of fonts in your web projects by dynamically loading hundreds of font

I am in possession of a directory called /assets/fonts containing a plethora of fonts that I wish to incorporate into a website in a dynamic manner. Users will be able to specify their font preferences, akin to a text editor. Individually assigning the fo ...

How to display a PDF in Angular 6 using a byte array retrieved from a WebAPI

Having trouble opening a PDF from byte array sent by WebAPI. This is my Service: fetchPdfDocument(): Observable<any> { return this.httpClient .get(this.configuration.serverUrl + this.configuration.getPdfDoc, { re ...

When defining a class property in TypeScript, you can make it optional by not providing

Is there a way to make a property on a Class optional without it being undefined? In the following example, note that the Class constructor takes a type of itself (this is intentional) class Test { foo: number; bar: string; baz?: string; construc ...

FabricJS Canvas with a React DropDown Feature

While I have successfully created a TextBox on FabricJS Canvas, creating a Dropdown component has proven to be a challenge. The fabric.Textbox method allows for easy creation of text boxes, but no such built-in method exists for dropdowns in FabricJS. If y ...

Transferring data from a child component to a parent component in Angular using @ViewChild requires providing 2 arguments

Currently, I am attempting to transmit data using @Output & EventEmitter and @ViewChild & AfterViewInit from a child component to a parent component. Below is the code from my parent component .html file: <app-child (filterEvent)=" getValu ...

Mastering the Implementation of Timetable.js in Angular with TypeScript

I am currently working on integrating an amazing JavaScript plugin called Timetable.js into my Angular6 project. You can find the plugin here and its repository on Github here. While searching for a way to implement this plugin, I stumbled upon a helpful ...

The BehaviorSubject will consistently emit identical values to each subscription

I am currently facing an issue with the BehaviorSubject where it emits a value for every subscription. This means that if I have, for example, 2 subscriptions to this.projectService.projectState$ streams using methods like async or tap, the projectState$ e ...

Analyzing elements within an array using Angular 4

I have an array filled with various Objects such as: [ {"id":1,"host":"localhost","filesize":73,"fileage":"2018-01-26 09:26:40"}, {"id":2,"host":"localhost","filesize":21,"fileage":"2018-01-26 09:26:32"}, {...} ] These objects are displayed in the fol ...

Deliver a securely authenticated single-page application on the root route through the use of a BFF, featuring a personalized login interface prior to employing Azure authentication

The scenario I'm dealing with is a bit complex, so bear with me as I try to explain it. In my ASP.NET Core 5 application, I've set up a BFF (backend for frontend) for my Angular app. The catch is that users must log in using Azure AD before acces ...

How come TypeScript doesn't recognize my MongoDB ObjectID as a valid type?

Currently, I am working with Node.js, MongoDB, and TypeScript. The code snippet below is error-free: const ObjectID = require("mongodb").ObjectID; const id = new ObjectID("5b681f5b61020f2d8ad4768d"); However, upon modifying the second line as follows: ...

Testing an HTTP error Observable with Jasmine and RxJS simulations

I encountered a similar issue, but due to commenting constraints on other questions, I had to create a new one. The problem lies in a jasmine test where a function is expected to manage an error from a service call. The service call returns an RxJS `Observ ...