Transfer data to transfer a repeating element from a repeating component

In Angular 2, I want to put something in a string ng-contentin the ngForinside of my component. But the problem is that I need to pass some ito data to transcluded.

I found the following solution for AgularJS:
http://plnkr.co/edit/aZKFqPJmPlfTVRffB0Cc?p=preview

.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">\
                        <placeholder></placeholder>\
                      </div>';
      var templateEl = angular.element(template);

      transclude(scope, function(clonedContent){
        templateEl.find("placeholder").replaceWith(clonedContent);

        $compile(templateEl)(scope, function(clonedTemplate){
          element.append(clonedTemplate);
        });
      });
    }
  };
});

How can I do the same in Angular 2?

PS: The same question in Russian.

+4
source share
1 answer

You can use ngForTemplateas follows:

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

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

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

Plunger example

Or instead template let-itemyou can write:

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

Plunger example

+3

Source: https://habr.com/ru/post/1648417/


All Articles