Adeel
Adeel

Reputation: 143

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables

onGetForm() {
  this.serverData.getData('questionnaire/Student Course Review')
    .subscribe(
       (response: Response) => {
          this.questionnaire = response.json();
          let key = Object.keys(this.questionnaire);
          for (let i = 0; i < key.length; i++) {
            this.currentQuestionsValue.push(this.questionnaire[key[i]])
          }
        },
        (error) => console.log('Form Error', error)
      )
  }

my html loop, Note: I simply want to iterate

<form>
  <div *ngFor="let data of currentQuestionsValue">
    <div *ngFor="let d of data.items ">
      <strong> {{ d.sno }}). </strong>
      <span>{{ d.question}}</span>
      <div *ngFor="let op of d.options">
        <label>
          <input type="radio" name="option">
          <span>{{ op }}</span>
        </label>
      </div>
    </div>
  </div>
</form>

I am getting following error when running a loop on json data.

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

I wanna display this items. enter image description here

Upvotes: 1

Views: 1100

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58573

Here options is not array , its just simple json object , because of the below line you are getting error :

<div *ngFor="let op of d.options">

Solution :

Component side :

objectKeys = Object.keys;

Template side :

<div *ngFor="let key of objectKeys(d.options)">
    <label>
        <input type="radio" name="option">
        <span>{{ d.options[key] }}</span>
    </label>
</div>

For reference : WORKING DEMO

Upvotes: 1

bereket gebredingle
bereket gebredingle

Reputation: 12996

This is becuase your second ngFor loop is trying to loop over an object.

The options value is an object with attribute 'option1','option2'...;

So you have to change this to array as you.

this.questionnaire = response.json();
      let key = Object.keys(this.questionnaire);
      for (let i = 0; i < key.length; i++) {
        this.currentQuestionsValue.push(this.questionnaire[key[i]])
      }
for( let j = 0; j < this.currentQuestionsValue.length ; j++) {
      this.currentQuestionsValue[j].options =  Object.keys(this.currentQuestionsValue[j].options).map(i => options[i])
   }

enter image description here

Upvotes: 0

Related Questions