Answer the question
In order to leave comments, you need to log in
How to implement passing a template as a parameter to a component in Angular 2?
I don’t know how to formulate this correctly in terms of Angular 2, but I’ll try to describe what I want to get in the end.
There is an Angular2 component that builds a table from an array of objects that I pass as a parameter. The last column will contain various buttons for performing an operation on each of the objects. The idea is to build these buttons (cells in the last column) dynamically based on the template passed as a parameter. In general, something like ng-content (ng-transclude in angular 1) only to work inside ngFor and have access to the context (the current object from the loop). Handlers must be in the parent, i.e. this component that builds the table should not know at all that there will be some buttons and handlers at all - it stupidly builds a table in a loop, takes a template in the last column, builds it and passes the context.
Something like this.
PS. Previously, I implemented something similar, but still buttons and handlers were built in the component itself according to the meta description. but this is quite a crutch solution.
Answer the question
In order to leave comments, you need to log in
Everything turned out to be EXTREMELY SIMPLE!!!
But, damn it, until it came to this, I almost dislocated my brain. There are no examples on the Internet at all, although it is strange because it seems like a use case is normal.
The solution turned out to be even more than working - it turned out to use several named templates within one component.
In general, in the parent component, we do this.
<datatable [items]="accounts">
<template #aa1 let-item="item">
Custom template for: <b>{{item.Name}}</b>
<button (click)="testTemplate(item)">From Template</button>
</template>
<template #aa2 let-item="item">
Custom template for: <i>{{item.Name}}</i>
<button (click)="testTemplate(item)">From Template</button>
</template>
</datatable>
@ContentChild('aa1') template1: TemplateRef<any>;
@ContentChild('aa2') template2: TemplateRef<any>;
...
<tr *ngFor="let item of items">
<td>
<template
[ngTemplateOutlet]="template1"
[ngOutletContext]="{item: item}">
</template>
</td>
<td>
<template
[ngTemplateOutlet]="template2"
[ngOutletContext]="{item: item}">
</template>
</td>
</tr>
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question