Pass data to transcluded repeated element from repeating component

独自空忆成欢 提交于 2019-12-10 06:06:20

问题


In Angular 2 I want to put something line ng-content into ngFor inside of my component. But the problem is I need to pass some data ito the transcluded element.

I found 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 make the same thing in Angular 2?

PS: Same question in Russian.


回答1:


You can use ngForTemplate like this:

@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];
}

Plunker example

Or instead template let-item you can write:

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

Plunker example



来源:https://stackoverflow.com/questions/38466490/pass-data-to-transcluded-repeated-element-from-repeating-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!