问题描述
我有一个只显示名称的列表组件。 list组件应该能够获取由用户提供的自定义模板。
I have a list component which shows only names. list component should be able to take custom template which will be given by user.
列表组件
import {Component } from 'angular2/core';
@Component({
selector: 'my-list',
template: `<p>This is List</p>
<ul>
<li *ngFor="#i of data"><div class='listItem'>{{i.name}}</div></li>
</ul>`
})
export class MyList implements OnInit{
data: Array<any> = [{name: 'John', age: 26},{name: 'Kevin', age: 26}, {name:'Simmons', age:26}];
}
我的要求
<my-list>
<div>{{i.name}}-{{i.age}}</div> //user should be able to provide custom template like this
</my-list>
我尝试使用ng-content,但它会抛出错误。在角度1同样的事情用于处理被抄除的内容。我们在角度2中有任何替代的手动转换,如果没有,那么我们如何在angular2中实现此功能。
I tried this with ng-content but it throws error. In angular 1 same thing used to work with transcluded content. do we have any alternative of manual transclusion in angular 2 and if not then how could we implement this feature in angular2.
这是
推荐答案
你需要为了使用ngForTemplate,我使用这种技术创建了PrimeNG DataList和许多其他DataComponents,它运行良好。演示;
You need to use ngForTemplate, I've created PrimeNG DataList and many other DataComponents using this technique and it works great. Demo;
代码;
在你的组件中,用contentchild定义templateRef;
In your component, define a templateRef with contentchild;
@ContentChild(TemplateRef) itemTemplate: TemplateRef;
您的模板变为;
template: `<p>This is List</p>
<ul>
<template ngFor [ngForOf]="data" [ngForTemplate]="itemTemplate"></template>
</ul>`
以便您的用户可以定义内容,如;
So that your users can define content like;
<my-list>
<template #anything>
<div>{{anything.i.name}}-{{anything.i.age}}</div>
</template>
</my-list>
这篇关于Angular2中列表组件的自定义模板(不包含ng-content的转换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!