Custom template(transclusion without ng-content) for list component in Angular2

二次信任 提交于 2019-11-27 23:19:11
Cagatay Civici

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

Code;

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

In your component, define a templateRef with contentchild;

@ContentChild(TemplateRef) itemTemplate: TemplateRef;

Your template becomes;

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>
Thierry Templier

There was a question regarding this in the past (see Use content of component template in angular 2) and this doesn't seem to be supported.

There are two things here:

  • When you provide an input template for the component, your i is variable is evaluated against the current component and not my-list one. If you want to use its properties you must do something like that:

    <my-list #myList>
      <div>{{myList.i.name}}-{{myList.i.age}}</div> //user should be able to provide custom template like this
    </my-list>
    
  • The other problem is the ability to use ng-content within a loop and it's not supported. I think that we could add an issue for this...

Here is a the plunkr I used for my tests: https://plnkr.co/edit/a06vVP?p=preview.

You can find a short interesting guide which shows you how to build such a list-component with custom-template here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!