[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.

This question is related to angular angular2-template angular-template

The answer is


it's not exact output that you wanted but maybe something like this will do. Parent cmp:

<table>
  <item *ngFor="#i of items" [data]="i"></item>
</table>

Child cmp

import {Component} from 'angular2/core';

@Component({
  selector: `item`,
  inputs: ['data'],
  template: `
    <tr><td>{{data.name}}</td></tr>
    <tr *ngFor="#i of data.items">
      <td><h1>{{i}}</h1></td>
    </tr>
  `
})
export default class Item {


}

Here is a basic approach - it sure can be improved - of what I understood to be your requirement.

This will display 2 columns, one with the groups name, and one with the list of items associated to the group.

The trick is simply to include a list within the items cell.

<table>
  <thead>
    <th>Groups Name</th>
    <th>Groups Items</th>
  </thead>
  <tbody>
    <tr *ngFor="let group of groups">
      <td>{{group.name}}</td>
      <td>
        <ul>
          <li *ngFor="let item of group.items">{{item}}</li>
        </ul>
      </td>
    </tr>
  </tbody>
</table>

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

Try this. The scope of local variables defined by "template" directive.

<table>
  <template ngFor let-group="$implicit" [ngForOf]="groups">
    <tr>
      <td>
        <h2>{{group.name}}</h2>
      </td>
    </tr>
    <tr *ngFor="let item of group.items">
                <td>{{item}}</td>
            </tr>
  </template>
</table>

I am a fan of keeping logic out of the template as much as possible. I would suggest creating a helper function that returns the data that you care about to the template. For instance:

getItemsForDisplay():String[] {
 return [].concat.apply([],this.groups.map(group => group.items));
};

<tr *ngFor="let item of getItemsForDisplay()"><td>{{item}}</td></tr>

This will let you keep your presentation free of special logic. This also lets you use your datasource "directly".


   <tbody  *ngFor="let defect of items">            
          <tr>
            <td>{{defect.param1}}</td>
            <td>{{defect.param2}}</td>
            <td>{{defect.param3}}</td>                
            <td>{{defect.param4}}</td>
            <td>{{defect.param5}} </td>
            <td>{{defect.param6}}</td>
            <td>{{defect.param7}}</td>           
          </tr>
          <tr>
            <td> <strong> Notes:</strong></td>
            <td colspan="6"> {{defect.param8}}
            </td>`enter code here`
          </tr>          
        </tbody>

You can use the template syntax of ngFor on groups and the usual syntax inside it for the actual rows like:

<table>
  <template let-group ngFor [ngForOf]="groups">
    <tr *ngFor="let row of group.items">{{row}}</tr>
  </template>
</table>

Check this plunk


This worked for me.

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

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to angular2-template

Please add a @Pipe/@Directive/@Component annotation. Error How to truncate text in Angular2? What is let-* in Angular 2 templates? angular2: Error: TypeError: Cannot read property '...' of undefined Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release) Angular2: Cannot read property 'name' of undefined How to prevent Browser cache on Angular 2 site? Angular 2 Scroll to top on Route Change <ng-container> vs <template> Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

Examples related to angular-template

How and where to use ::ng-deep? How to use *ngIf else? Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays Dynamic tabs with user-click chosen components Getting reference to child component in parent component How to use Angular2 templates with *ngFor to create a table out of nested arrays? What is the equivalent of ngShow and ngHide in Angular 2+? Angular: conditional class with *ngClass