我有一个只显示名字的列表组件。列表组件应该能够采用用户提供的自定义模板。
列表组件
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 试过了,但它抛出了错误。在 Angular 1 中,同样的事情用于处理嵌入的内容。我们在 angular 2 中是否有任何替代手动嵌入的方法?如果没有,我们如何在 angular2 中实现此功能。
这里是 Plunker
最佳答案
您需要使用 ngForTemplate,我已经使用这种技术创建了 PrimeNG DataList 和许多其他 DataComponents,并且效果很好。演示;
http://www.primefaces.org/primeng/#/datalist
代码;
https://github.com/primefaces/primeng/blob/master/src/app/components/datalist/datalist.ts
在您的组件中,定义一个带有 contentchild 的 templateRef;
@ContentChild(TemplateRef) itemTemplate: TemplateRef;
您的模板变为;
template: `<p>This is List</p>
<ul>
<template ngFor [ngForOf]="data" [ngForTemplate]="itemTemplate"></template>
</ul>`
这样您的用户就可以定义内容;
<my-list>
<template #anything>
<div>{{anything.i.name}}-{{anything.i.age}}</div>
</template>
</my-list>
关于javascript - Angular2 中列表组件的自定义模板(没有 ng-content 的包含),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36531503/