将数据传递给重复组件

时间:2016-07-19 18:59:44

标签: angularjs angular transclusion

在Angular 2中,我想在我的组件内部放置ng-contentngFor。但问题是我需要将一些数据传递给被转换的元素。

found遵循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);
        });
      });
    }
  };
});

如何在Angular 2中做同样的事情?

PS:Same question in Russian.

1 个答案:

答案 0 :(得分:3)

您可以像这样使用ngForTemplate

@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

或者template let-item你可以写:

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

<强> Plunker example