Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 multiple TemplateRef

Tags:

angular

I am trying to build a custom datagrid that can display data either as cards or the more tradional table/list/grid. I can do it pretty easily if I do not want the templates to be customizable as shown in this plunker

Here I have a my-grid component that gets passed the data to be rendered. Then I loop over the data and render the card-view or list-view component depending on the desired view which is controlled by the view toggle (code in app/my-grid.ts file)

I want to provide the ability to pass in custom templates and I am thinking something like this:

<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 from where I am at?

like image 944
mithun_daa Avatar asked Feb 24 '16 22:02

mithun_daa


1 Answers

I was able to solve my issue 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 it helps anyone else that is facing a similar problem. Or maybe someone can point me to a better solution

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

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

like image 104
mithun_daa Avatar answered Sep 28 '22 17:09

mithun_daa