Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

angular - How to use Angular2 templates with *ngFor to create a table out of nested arrays?

Given the following array in component property groups:

[
   {
     "name": "pencils",
     "items": ["red pencil","blue pencil","yellow pencil"]
   },
   {
     "name": "rubbers",
     "items": ["big rubber","small rubber"]
   },
]

How to create a html table with all items, each in one row? The expected HTML result:

<table>
    <tr><td><h1>pencils</h1></td></tr>
    <tr><td>red pencil</td></tr>
    <tr><td>blue pencil</td></tr>
    <tr><td>yellow pencil</td></tr>
    <tr><td><h1>rubbers</h1></td></tr>
    <tr><td>big rubber</td></tr>
    <tr><td>small rubber</td></tr>
</table>

The first level is easy:

<table>
    <tr *ngFor="#group of groups">
        <td><h1>{{group.name}}</h1></td>
    </tr>
</table>

But now I have to iterate #item of group. The problem is that I need the new <tr> elements after the </tr> element which defines group, not inside.

Is there any solution for this kind of problems in Angular2 templating? I would expect some special tag which I could use instead of <tr> which is not written into the dom. Something similar to facets and fragments in JSF.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
<table>
     <ng-container *ngFor="let group of groups">
         <tr><td><h2>{{group.name}}</h2></td></tr>
         <tr *ngFor="let item of group.items"><td>{{item}}</td></tr>
     </ng-container>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...