I am trying to build a listing component in Angular2 that takes the items, the columns and the templates for the fields of the items from the user of the component. So I am
This is how you need to do this:
@Component({
selector: 'my-component',
template: `
<div *ngFor="let item of items">
<span *ngFor="let column of columns">
<template [ngTemplateOutlet]="column.ref" [ngOutletContext]="{ item: item }"></template>
</span>
</div>`
})
export class MyComponent {
@Input() items: any[];
@Input() columns: any[];
}
@Component({
selector: 'my-app',
template: `
<div>
<my-component [items]="cars" [columns]="columns">
<template #model let-item="item">{{item?.model}}</template>
<template #color let-item="item">{{item?.color}}</template>
</my-component>
</div>`
})
export class App {
@ViewChild('model') model;
@ViewChild('color') color;
cars = [
{ model: "volvo", color: "blue" },
{ model: "saab", color: "yellow" },
{ model: "ford", color: "green" },
{ model: "vw", color: "orange" }
];
ngAfterContentInit() {
this.columns = [
{ ref: this.model },
{ ref: this.color ]
];
}
}
Plunker
you can do it without ngOutletContext. You have to use ng-template instead of template. following code works for me:
app.component.html:
<div>
<ng-template #c1>
<app-child1></app-child1>
</ng-template>
<app-parent [templateChild1]="c1"></app-parent>
</div>
app-parent is a child of app-component. app-child is declared in app-component as template and this template is used in app-parent.
app.parent.html:
<p>
<ng-template [ngTemplateOutlet]="templateChild1"></ng-template>
</p>
app.parent.ts:
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
@Input() public templateChild1: TemplateRef<any>;
public ngOnInit() {
}
}
update Angular 5
ngOutletContext
was renamed to ngTemplateOutletContext
See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
original
Don't use []
and {{}}
together. Either the one or the other but not both.
Don't use {{}}
if you want to pass an object because {{}}
is for string interpolation.
It should be
[ngTemplateOutlet]="column.templateRef"
Plunker example