7

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?

1
  • You might have a look at the source of other structural directives like *ngFor. I had a brief look but don't have a working example of a custom implementation myself yet. Commented Feb 25, 2016 at 6:07

1 Answer 1

4

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;

Sign up to request clarification or add additional context in comments.

1 Comment

It does still work for me, both in beta and RC. The only difference in RC being that you need to use forwardRef(). Updated the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.