Angular2中列表组件的自定义模板(不包含ng-content的转换) [英] Custom template(transclusion without ng-content) for list component in Angular2

查看:388
本文介绍了Angular2中列表组件的自定义模板(不包含ng-content的转换)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个只显示名称的列表组件。 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.

这是 Plunker

推荐答案

你需要为了使用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;

http:// www .primefaces.org / primeng /#/ datalist

代码;

https://github.com/primefaces/primeng/blob/ master / src / app / components / datalist / datalist.ts

在你的组件中,用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的转换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆