问题
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