Angular 2 Multiple TemplateRef

I am trying to create a custom datagrid that can display data both in the form of maps and in a more traditional table / list / grid. I can do this quite easily if I don't want the templates to be customized as shown in this plunker

Here I have a my-grid component that receives the transferred data. Then I iterate over the data and process the card-view or list-view component depending on the desired view, which is controlled by view toggle (the code in the app/my-grid.ts )

I want to provide the ability to pass in custom templates, and I think the following:

 <my-grid> <card-view-template> <template var-item> <h4>{{item.name}}</h4> {{item.home}} </template> </card-view-template> <list-view-template> <template var-item> <span>{{item.name}}</span> {{item.home}} </template> </card-view-template> </my-grid> 

How can I get to what I want, where am I from?

+6
source share
1 answer

I managed to solve my problem as shown here

 import {Component, Directive, ContentChild, TemplateRef} from 'angular2/core'; @Directive({ selector: 'card-view' }) export class CardViewComponent { @ContentChild(TemplateRef) itemTmpl; ngAfterContentInit() { console.log('In CCV', this.itemTmpl) } } 

Hope this helps someone else facing a similar issue. Or maybe someone can point me to a better solution.

Update: For newer versions of ng2 (RC at the time of writing this), you will need to use forwardRef() in some cases:

@ContentChild(forwardRef(() => CardViewComponent)) cardViewComponent; @ContentChild(forwardRef(() => ListViewComponent)) listViewComponent;

+4
source

All Articles