My simplified goal is to build a component which is a list with item template. E.g.:
<list>item</list>
Here is my code:
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
@Component({
selector: 'list',
template: `
<ul>
<li *ngFor="let i of items" >
<ng-content></ng-content>
</li>
</ul>
`
})
class List {
items = [1, 2, 3];
}
@Component({
selector: 'app',
directives: [List],
template: '<list>item</list>'
})
class App { }
bootstrap(App, []);
Expected result:
Actual result:
•
•
• item
I found 3 ways to do it
@Component({
selector: 'dynamic-list',
template: '<div *ngFor="#item of items" *ngForTemplate="itemTemplate"></div>'
})
export class DynamicListComponent {
@ContentChild(TemplateRef)
public itemTemplate: TemplateRef;
@Input()
public items: number[];
}
<dynamic-list [items]="items">
<div template="#item">
Inline template item #: {{item}}
</div>
</dynamic-list>
output:
Inline template item #: 1
Inline template item #: 2
Inline template item #: 3
Inline template item #: 4
plunker: https://plnkr.co/edit/ollxzUhka77wIXrJGA9t?p=preview
see more https://github.com/ilio/ng2-dynamic-components/blob/master/README.md