Qwertiy Qwertiy - 1 year ago 111
AngularJS Question

Pass data to transcluded repeated element from repeating component

In Angular 2 I want to put something line

inside of my component. But the problem is I need to pass some data ito the transcluded element.

I found following solution for AgularJS:


.directive("foo", function($compile){
return {
scope: {},
transclude: true,
link: function(scope, element, attrs, ctrls, transclude){

scope.items = [1, 2, 3, 4];

var template = '<h1>I am foo</h1>\
<div ng-repeat="$item in items">\
var templateEl = angular.element(template);

transclude(scope, function(clonedContent){

$compile(templateEl)(scope, function(clonedTemplate){

How can I make the same thing in Angular 2?

PS: Same question in Russian.

Answer Source

You can use ngForTemplate like this:

    selector: 'foo',
    template: `
        <h1>I am foo</h1>
         <template ngFor [ngForOf]="data" [ngForTemplate]="itemTemplate"></template>
export class Foo {
    @Input() data: any[];
    @ContentChild(TemplateRef) itemTemplate: TemplateRef<any>;

  selector: 'my-app',
  template: `<h1>Angular 2 Systemjs start</h1>
    <foo [data]="items">
        <template let-item>
            <div>item: {{item}}</div>
  directives: [Foo],

export class AppComponent {
    items = [1, 2, 3, 4];

Plunker example

Or instead template let-item you can write:

<foo [data]="items">
   <div template="let item">item: {{item}}</div>

Plunker example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download