Filout
Filout

Reputation: 101

*ngFor for JSON array

I've the following JSON struct

{
"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"
    }]
}}

Q: How can i make a *ngFor about all addesses?

Thanks in advance and regards Filout

Upvotes: 0

Views: 138

Answers (4)

Filout
Filout

Reputation: 101

I read that but i don't understand the solution. I tried the following in ".ts":

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

That works for me. Than i've another function like this:

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

If i set a breakpoint in constructor i can see this.formGroup.controls.addresses.controls.address with values but my IDE (Webstorm) say "Property 'controls' does not exist on type 'AbstractControl'"

Why this?

Upvotes: 0

Filout
Filout

Reputation: 101

Thanks for your quick reply. But what does ERROR TypeError: this.form._updateTreeValidity is not a function mean in the following code?

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

Upvotes: 0

Piyush Jain
Piyush Jain

Reputation: 1986

do like this.

in 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 html

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

let me know if you have any doubt.

Upvotes: 1

Shlok Nangia
Shlok Nangia

Reputation: 2377

you can do it like this

in ts file

this.adressList= data.adresses.adress

in html file

<div *ngFor="let adress of adressList">
   {{adress.info1}}
</div>

Upvotes: 2

Related Questions