1

I want to render JSON data as separate list-item elements in view via Pipe in my Angular2 app, but my code isn't working.

My JSON data (I load it via http):

[
 {
   "name": "Release One",
   "songs": [
     "Song 1",
     "Song 2",
     "Song 3"
   ],
   "year": "2008"
 },
 {
   "name": "Release Two",
   "songs": [
     "Song 1",
     "Song 2",
     "Song 3",
     "Song 4",
     "Song 5"
   ],
   "year": "2010"
 },
 {
   "name": "Release Three",
   "songs": [
     "Song 1",
     "Song 2",
     "Song 3",
     "Song 4"
   ],
   "year": "2011"
 },
 {
   "name": "Release Four",
   "songs": [
     "Song 1",
     "Song 2",
     "Song 3",
     "Song 4",
     "Song 5"
    ],
   "year": "2011"
 }
]

My @Pipe according to the solution offered here:

@Pipe({name: 'KeysPipe'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    if (!value) {
      return value;
    } 

    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    } 
    return keys;
  } 
} 

My @Component:

@Component({
  selector: 'my-app',
  template: `
    <div class="releases-component">
      Releases Component starts here!
      <div *ngFor="let release of releases">
        <h3>Name: {{release.name}}</h3>
        <h3>Name: {{release.year}}</h3>
      </div>
    </div>

    <ul>
      <li *ngFor="let release.song of releases | keys">
        {{release.song}}
      </li>
    </ul>
  `,
})

Plunker example

Please, help understand what I am doing wrong.

Community
  • 1
  • 1
Alexandr Belov
  • 1,804
  • 9
  • 30
  • 43
  • I don't understand the latter iteration... what are you trying to accomplish with `let release.item of releases`. There is no `release.item` in your json? What do you want rendered there? Could you give an example of your desired output in your question, thanks. – AT82 Jan 12 '17 at 19:51

1 Answers1

1

Hopefully I understood you correctly and you do want to iterate the items, item by item. Well that can be accomplished fairly easily. Just nesting an *ngFor like so:

<div class="releases-component">
  <div *ngFor="let release of releases">
    <h3>Name: {{release.name}}</h3>
    <h3>Year: {{release.year}}</h3>
    <li *ngFor="let song of release.songs">{{song}}</li>
  </div>
</div>

That would output nicely:

Name: Release One
Year: 2008
Song 1
Song 2
Song 3

Name: Release Two
Year: 2010
Song 1
Song 2
Song 3
Song 4
Song 5

.... and so on...

EDIT: Working plunker

AT82
  • 71,416
  • 24
  • 140
  • 167