Angular 2 Template as a parameter to component
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
PLUNKER
AFAI tried <ng-content>
can't be binded repeatedly, but you can pass item
as input, like this
import {Component} from 'angular2/core';
@Component({
selector: 'list',
inputs: ['htmlIN'],
template: `
<ul>
<li *ngFor="#i of items" >
{{i}} {{htmlIN}}
</li>
</ul>
`
})
export class List {
htmlIN: any;
items = [1, 2, 3, 4];
}
@Component({
selector: 'my-app',
directives: [List],
template: `<list htmlIN="item"></list>`
})
export class App {
constructor(){
}
}
This is how I did it:
Usage:
<ng-template #myTemplate let-item="item">
<strong>Name: </strong> {{item.name}}<br>
<strong>Id: </strong> {{item.id}}
</ng-template>
<app-template-param [items]="items" [template]="myTemplate"></app-template-param>
Component:
@Component({
selector: 'app-template-param',
templateUrl: 'template-param.html'
})
export class TemplateParamComponent implements OnInit {
@Input() items: Array<any>;
@Input() template: TemplateRef<any>;
}
Component HTML
<ng-template #defaultTemplate let-item="item">
<strong>{{item.name}}</strong>
</ng-template>
<ul>
<li *ngFor="let item of items">
<ng-template [ngTemplateOutlet]="template || defaultTemplate" [ngTemplateOutletContext]="{item: item}"></ng-template>
</li>
</ul>