Tom Rudge
Tom Rudge

Reputation: 3272

Angular reactive form *ngFor loop, cannot read 'property' of undefined

StackBlitz example

I'm trying to loop dynamic values to create radio button items on my form. I have managed to display the three radio buttons coming from my data:

radiot: [
        {
          section: "yes",
          sectionCode: "1"
        },
        {
          section: "no",
          sectionCode: "2"
        },
        {
          section: "maybe",
          sectionCode: "3"
        }
      ]

The problem is I cant display the option of "section".

e.g.

<div class="form-check-inline" *ngFor="let item of personal.radioButtons.radiot; let i = index">

    <label for="yes" class="col-12 customradio"
        ><span>{{item[i].section}}</span>
        <input value="{{item[i].section}}" id="{{item[i]}}" type="radio" [formControlName]="i"/>
        <span class="checkmark"></span>
    </label>
</div>

What am I doing wrong? getting the error - Cannot read property 'section' of undefined

StackBlitz example

Upvotes: 0

Views: 386

Answers (3)

Damian C
Damian C

Reputation: 2171

Change your template from [formControlName] to formControlName

        <label for="{{item.section}}" class="col-12 customradio"
            ><span>{{item.section}}</span>
            <input value="{{item.section}}" name="formGroupName" id="{{item.section}}" type="radio" formControlName="radiot"/>
            <span class="checkmark"></span>
        </label>

As it is currently written you were telling angular to look for a variable named radiot which is undefined, but what it needs is a string so it can look for it as a property on the current form object

Upvotes: 1

Eudz
Eudz

Reputation: 598

You should put = instead of :

radiot = [
  {
    section: "yes",
    sectionCode: "1"
  },
  {
    section: "no",
    sectionCode: "2"
  },
  {
    section: "maybe",
    sectionCode: "3"
  }
];

Upvotes: 0

Sam
Sam

Reputation: 1861

You don't need to use i in *ngFor you already have reference to the object at that position.

So for the first iteration your item would be

{
          section: "yes",
          sectionCode: "1"
}

So you can just do item.section - no need for the index position.

<span>{{item.section}}</span>

Upvotes: 2

Related Questions