angularjs – 将数据传递给重复组件的transcluded重复元素

前端之家收集整理的这篇文章主要介绍了angularjs – 将数据传递给重复组件的transcluded重复元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Angular 2中,我想在我的组件内部添加ng-content ng ng内容.但问题是我需要将一些数据传递给transcluded元素.

我在found以下的AgularJS解决方案:@H_301_10@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.

解决方法

您可以像这样使用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,4];
}

Plunker example

或者代之以模板let-item你可以写:

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

Plunker example

猜你在找的Angularjs相关文章