Iterating over a JSON array using *ngFor

Here is the JSON structure that I have:

{
"first_name": "Peter",
"surname": "Parker",
"adresses": {
    "adress": [{
        "info1": "intern",
        "info2": "bla1"
    }, {
        "info1": "extern",
        "info2": "bla2"
    }, {
        "info1": "group",
        "info2": "bla3"
    }, {
        "info1": "outdoor",
        "info2": "bla4"
    }, {
        "info1": "indoor",
        "info2": "bla5"
    }]
}}

Question: How can I utilize *ngFor to loop through all addresses?

Thank you in advance and best regards, Filout

Answer №1

Here is a simple way to achieve this:

In the TypeScript file:

this.addressList = data.addresses.address

In the HTML file:

<div *ngFor="let address of addressList">
   {{address.info1}}
</div>

Answer №2

Follow these steps.

Open your component.ts file

data = {
    "first_name": "Peter",
    "surname": "Parker",
    "adresses": {
        "adress": [{
            "info1": "intern",
            "info2": "bla1"
        }, {
            "info1": "extern",
            "info2": "bla2"
        }, {
            "info1": "group",
            "info2": "bla3"
        }, {
            "info1": "outdoor",
            "info2": "bla4"
        }, {
            "info1": "indoor",
            "info2": "bla5"
        }]
    }
  }
  address = this.data.adresses.adress

In the HTML file

<div *ngFor="let value of address">
  {{value.info1}} - {{value.info2}}
</div>

If you encounter any confusion, feel free to ask me.

Answer №3

Thank you for getting back to me so quickly. I'm a bit confused about the meaning of ERROR TypeError: this.form._updateTreeValidity is not a function in the code snippet below:

<div *ngFor="let address of addressList">
    <div [formGroup]="address">
      <input formControlName="info1">
    </div>
</div>

Answer №4

I've gone through the information provided, but I am still confused about the solution. When working in ".ts", I attempted the following:

constructor(...) {
    this.formGroup = this.fb.group(...)
    this.formGroup.addControl('addresses', this.fb.group({
        address: new FormArray([])
    }))

This approach worked for me initially. However, I encountered another function that looked like this:

public get objControl(): FormArray {
        return this.formGroup.controls.addresses.controls.address as FormArray
    }

Although I can see values in

this.formGroup.controls.addresses.controls.address
when setting a breakpoint in the constructor, my IDE (Webstorm) throws an error stating "Property 'controls' does not exist on type 'AbstractControl'."

Can someone help me understand why this is happening?

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

Retrieve objects from an array that contain a certain specified key

I am trying to extract the objects from All_reports that contain the key: comentarioAdmin. Currently, I am retrieving all reports from All_reports, but I only want the reports that have the key comentarioAdmin. Thank you! getReports() { this.Service.g ...

Facing dilemmas with JSON parsing

I am currently working on a project using the Poke api to develop a simplified version of a pokedex. The objective is to allow users to input a pokemon's name and retrieve specific details about that pokemon. While I am able to display the entire json ...

Retrieve the :id parameter from the URL as a numerical value in Node.js using Typescript

Is there a way to directly get the :id param from the URL as a number instead of a string in order to easily pass it on to TypeORM for fetching data based on a specific ID? Currently, I am using the following approach where I have to create an additional ...

Showing dynamic icons in Angular 2 applications

My goal is to dynamically load a part of my website, specifically by using icon classes defined in the interface like this: import { OpaqueToken } from "@angular/core"; import {IAppConfig} from './app.interface' export let APP_CONFIG = new Opaq ...

Need to import Vue component TWICE

My question is simple: why do I need to import the components twice in the code below for it to function properly? In my current restricted environment, I am unable to utilize Webpack, .vue Single File Components, or npm. Despite these limitations, I mana ...

Utilizing MakeStyles from Material UI to add styling to a nested element

I was pondering the possibility of applying a style specifically to a child element using MakesStyles. For instance, in a typical HTML/CSS project: <div className="parent"> <h1>Title!</h1> </div> .parent h1 { color: # ...

Tips for resolving a typescript Redux connect error related to ActionCreatorsMapObject

Encountering typescript error: ERROR in [at-loader] ./src/app/components/profile/userProfile/_userMain.tsx:130:37 TS2345: Argument of type 'typeof "/usr/src/app/src/js/src/app/redux/actions/sessionActions"' is not assignable to parameter of ...

Performing actions simultaneously with Angular 2 directives

My custom directive is designed to prevent a double click on the submit button: import { Directive, Component, OnInit, AfterViewInit, OnChanges, SimpleChanges, HostListener, ElementRef, Input, HostBinding } from '@angular/core'; @Directive({ ...

Passing an array from the PHP View to a JavaScript function and plotting it

Greetings, I am currently facing the following tasks: Retrieving data from a database and saving it to an array (CHECK) Sending the array from Controller to View (CHECK) Passing that array to a JavaScript function using json_encode (CHECK) Plotting the ...

RestClientException: Unable to retrieve response. Could not locate appropriate HttpMessageConverter

When I use the curl command like this: curl -u 591bf65f50057469f10b5fd9:0cf17f9b03d056ds0e11e48497e506a2 https://backend.tdk.com/api/devicetypes/59147fd79e93s12e61499ffe/messages I receive a JSON response: {"data":[{"device":"18SE62","time":1494516023," ...

How can we bring in a JavaScript file to an Angular 2 project?

I've been struggling with importing a JavaScript file into my Angular2 project. This particular file is not a module from npm, and the usual instructions using npm don't apply in this case. My setup involves using Angular CLI, and within my angu ...

Merge the data from various sections of a JSON object into a unified array

Upon completing an ajax call to a specific URL, I receive data in the form of a JSON object structured like this: {"field1":["val1","val2","val3",...,"valn"], "field2":["vala","valb","valc",...,"valx"]} My goal is to merge the values of field1 and field ...

Strategies for Obtaining a Response Following a Function Execution in React JS

Hello, I am encountering an issue where I am calling a function and trying to get a response, but it is returning undefined. The response is being passed from the parent component to the child component. Here is the code for the component: import React fr ...

Error: The variable $ has not been defined in the JSON data

I am exploring the use of JSON for the first time and attempting to implement the following code: var url = 'http://where.yahooapis.com/geocode?q=Vancouver&flags=J&count=10&lang=en&appid=' + myAppId + '&callback=?'; ...

Error: Prisma seed - encountering issues with undefined properties (unable to read 'findFirst')

I've encountered a strange issue when using prisma seed in my nextjs full-stack project that I can't seem to figure out. Normally, when running the app with `next dev`, everything works smoothly and the queries are executed without any problems. ...

Formatted JSON displaying a table view with an alert view

In my XCode project, there is a View Controller that handles JSON parsing from a MySQL Database to populate a table view. This app assists in creating school schedules. My goal is to enable users to add a selected class to another table view by clicking on ...

Tips for sending a file rather than a json object in nextjs

Is there a way to send a file from either route.ts or page.ts, regardless of its location in the file-system? Currently, I am using the following code in my back-end python + flask... @app.route("/thumbnail/<string:filename>") def get_file ...

Obtain PHP array after making an AJAX request

I'm using $.post() to send a JavaScript object and I need to receive an array in return. JavaScript Code var ajaxData = {action:"createuser"} $("input[required]").each(function(){ var attr = $(this).attr("name"); ajaxData[attr] = $(this).val ...

Issue encountered with JavaScript function within TypeScript file connected to HTML code

I am currently working on a simple SharePoint web part and encountering an issue with using a function from another module file in my main file. Snippet from the JSFunctions.module.js file (where I define my function): function getApi(){ [my code]... }; ...

Navigate to a different page using Angular2 routing

Looking for guidance on using redirect in the new Angular 2 router. Specifically interested in examples similar to 'redirectTo' from the beta version. Any demos on 'plnkr.co' would be greatly appreciated! ...