0

How can I change this in my controller

types = {
   'fru':   'Fruits',
   'veg':   'Vegetables',
};

in a way that allows me to do this in my view (a)

<span class="value">{{ types['fru'] }}</span>

and this in my view (b)

<div *ngFor="let value of types">
    {{ value }}
</div>

?

At the moment, (a) works fine, and (b) throws "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

I understand that my object cannot be iterated over. My question is, is there a way to change my object in my controller to another data structure in order to be able to achieve both desired functionalities in my view?

Ben
  • 15,938
  • 19
  • 92
  • 138
  • 1
    Possible duplicate of [Angular2 - \*ngFor / loop through json object with array](https://stackoverflow.com/questions/43215049/angular2-ngfor-loop-through-json-object-with-array) – Vivek Doshi Feb 06 '18 at 07:06
  • I think for iterate over for-loop `types` should be `[{ "fru": "Fruits", "veg": "Vegetables" }]` array list. – hrdkisback Feb 06 '18 at 07:07
  • @hrdkisback , its just little bit of code change and you can achive the same thing its about logic , not the exact code . You can also check the answer I have posted below to show. – Vivek Doshi Feb 06 '18 at 07:11
  • @Vivek, Yeah I see for this error ` "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."` I commented :). – hrdkisback Feb 06 '18 at 07:18

3 Answers3

2

Here you go :

Component Side :

objectKeys = Object.keys;
data = {
    'fru':   'Fruits',
    'veg':   'Vegetables',
};

Template Side :

<ul>
    <li *ngFor='let key of objectKeys(data)'>
        Key: {{key}}, value: {{data[key]}}
    </li>
</ul>

WORKING DEMO

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
1

you can use

*ngFor="let t of templates | keyvalue"

https://angular.io/api/common/KeyValuePipe

0

You can't iterate over an object,*ngFor works only with arrays.

What you can actually do is create and use a pipe to convert the object key-values to an array and iterate it:

@Pipe({ name: 'keyValue' })
export class KeyValuePipe implements PipeTransform {
  transform(value, args: string[]): any {
    let keys = [];
    for (let key in value) {
      keys.push({ key: key, value: value[key]});
    }
    return keys;
  }
}

Example usage:

<ul>
  <li *ngFor='key of demo | keyValue'>
     Key: {{key.key}}, value: {{key.value}}
  </li>
</ul>
TheUnreal
  • 23,434
  • 46
  • 157
  • 277
  • (1) How do I implement the pipe in my code? I have copied it into my controller and get: Uncaught Error: Template parse errors: The pipe 'keyValue' could not be found... (2) As explained, I ideally am looking for a different data structure to achieve this, what about an Array or a Map, anything? – Ben Feb 06 '18 at 07:13