Custom template(transclusion without ng-content) for list component in Angular2

I have a list component which shows only names. list component should be able to take custom template which will be given by user.

List Component

import {Component } from 'angular2/core';

  selector: 'my-list',
  template: `<p>This is List</p>
       <li *ngFor="#i of data"><div class='listItem'>{{}}</div></li>
export class MyList implements OnInit{ 
    data: Array<any> = [{name: 'John', age: 26},{name: 'Kevin', age: 26},  {name:'Simmons', age:26}];

My Requirement

   <div>{{}}-{{i.age}}</div> //user should be able to provide custom template like this

I tried this with ng-content but it throws error. In angular 1 same thing used to work with transcluded content. do we have any alternative of manual transclusion in angular 2 and if not then how could we implement this feature in angular2.

Here is Plunker



You need to use ngForTemplate, I've created PrimeNG DataList and many other DataComponents using this technique and it works great. Demo;


In your component, define a templateRef with contentchild;

@ContentChild(TemplateRef) itemTemplate: TemplateRef;

Your template becomes;

template: `<p>This is List</p>
       <template ngFor [ngForOf]="data" [ngForTemplate]="itemTemplate"></template>

So that your users can define content like;

   <template #anything>

There was a question regarding this in the past (see Use content of component template in angular 2) and this doesn't seem to be supported.

There are two things here:

  • When you provide an input template for the component, your i is variable is evaluated against the current component and not my-list one. If you want to use its properties you must do something like that:

    <my-list #myList>
      <div>{{}}-{{myList.i.age}}</div> //user should be able to provide custom template like this
  • The other problem is the ability to use ng-content within a loop and it's not supported. I think that we could add an issue for this...

Here is a the plunkr I used for my tests:


You can find a short interesting guide which shows you how to build such a list-component with custom-template here.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.