0

My goal is to create a component that can take a custom element and iterate over it using provided data.

Here is what i have been able to come up with, and it works fine. But i'm not satisfied. I want something that does not require wrapping the custom element in a <template> tag.

import {Component, Input, Output, EventEmitter} from 'angular2/core';

@Component({
  selector: 'sub',
  template: `
    <ng-content></ng-content>
  `
})
export class SubComponent  {}

@Component({
  selector: 'my-app',
  template: `
    <sub>
      <template ngFor #listItem [ngForOf]="list" #i="index"> //<--don't want this tag
        <div>{{listItem | json}}</div>
        <p>{{i}}</p>
      </template>
    </sub>
  `,
  directives: [ SubComponent ]
})

export class AppComponent {
  list = [{name: 'John', age: 26},{name: 'Kevin', age: 26},          {name:'Simmons', age:26}];
}
  • the code above is an edit of this plunker.
  • seen the suggestion here but were quite vague.
Community
  • 1
  • 1
Isaiahiroko
  • 994
  • 7
  • 12
  • Have you taken a look at using [`@Input`](https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child) to pass the list to the sub component? – Christopher Moore May 05 '17 at 09:25
  • The list array can be passed using `@Input`, however, that won't solve the problem of wrapping the custom element in a `template` tag. – Isaiahiroko May 05 '17 at 09:54
  • I'm not sure I understand. If you use `@Input` you don't need `ng-content` in your `sub` component – Christopher Moore May 05 '17 at 10:01
  • thanks @ChristopherMoore. Eventually solved the problem. My answer below shows what I wanted to achieve. – Isaiahiroko May 06 '17 at 09:23

1 Answers1

0

Discovered here that i could use a directive on ng-content transclusion (early versions of ng2 do not), so the solution is as simple as follows:

import {Component, Input, Output, EventEmitter} from 'angular2/core';

@Component({
    selector: 'sub',
    template: `
        <p>content</p>

        <ng-content></ng-content>

        <p>more content</p>

    `
})
export class SubComponent  {}

@Component({
    selector: 'my-app',
    template: `
        <sub >
            <any-element *ngFor="let listItem of list" >
                {{ listItem | json }}
            </any-element>
        </sub>
    `
})

export class AppComponent {
    list = [{name: 'John', age: 26},{name: 'Kevin', age: 26}, {name:'Simmons',     age:26}];
}
Isaiahiroko
  • 994
  • 7
  • 12