在Angular 2中,我想在我的组件内部放置ng-content
行ngFor
。但问题是我需要将一些数据传递给被转换的元素。
我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中做同样的事情?
答案 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 强>