ranjeet8082
ranjeet8082

Reputation: 2359

Dynamic rowspan in angular

Number of persons and their mobiles numbers are dynamic. I need to show this in table.

Data can contain any number of pname and mobile numbers.

dataList = [
 {
  pname: "abc",
  numbers: [{mobile1: 123, mobile2: 234}]
 },
{
  pname: "mno",
  numbers: [{mobile1: 125, mobile2: 237}]
 }
]

Template

<tr *ngFor="let data of dataList">
 <td  [attr.rowspan]="data.numbers.lenght">data.pname</td>
 <td>data.numbers</td> // Here how do I show all mobile numbers of the person.
</tr>

Expected output is of below code.

table, th, td {
    border: 1px solid black;
}
<table>
  <tr>
    <th>Pname</th>
    <th>Numbers</th>
  </tr>
  <tr>
    <td rowspan="2">Abc</td>
    <td>123</td>
  </tr>
  <tr>
    <td>234</td>
  </tr>
  <tr>
    <td rowspan="2">Mno</td>
    <td>125</td>
  </tr>
  <tr>
    <td>237</td>
  </tr>
</table>

Problem I am facing is I need to add tr after each run of *ngFor and the number of tr will depend on length of numbers array to make row span.

Upvotes: 13

Views: 28782

Answers (3)

Yasser Bazrforoosh
Yasser Bazrforoosh

Reputation: 1296

it is simple to use two *ngFor and avoid repeat Code by data.numbers[0].

<table>        
  <ng-container *ngFor="let data of dataList">    
   <ng-container *ngFor="let number of data.numbers; let i= index;">
     <tr>
        <td *ngIf="i==0" [attr.rowspan]="data.numbers.length">{{data.pname}}</td>
        <td>{{number}}</td>
     </tr>
   </ng-container>
  </ng-container>
</table>

Upvotes: 1

kohashi
kohashi

Reputation: 321

Simple.

You don't need index and nested ng-container.

<table>
    <ng-container *ngFor="let data of dataList">
        <tr>
            <td [attr.rowspan]="data.numbers.length + 1">{{data.pname}}</td>
        </tr>
        <tr *ngFor="let number of data.numbers;">
          <td>{{number}}</td>
        </tr>
    </ng-container>
</table>

Working example. https://stackblitz.com/edit/angular-yrose8?file=src%2Fapp%2Fapp.component.html

Upvotes: 7

Nandita Sharma
Nandita Sharma

Reputation: 13407

You can do it like shown below

<table>        
    <ng-container *ngFor="let data of dataList">    
        <tr>
            <td [attr.rowspan]="data.numbers.length">{{data.pname}}</td>
            <td>{{data.numbers[0]}}</td>
        </tr>
        <ng-container *ngFor="let number of data.numbers; let i= index;">
            <tr *ngIf="i!=0">
                <td>{{number}}</td>
            </tr>
        </ng-container>
    </ng-container>
</table>

But datalist must be of the following format i.e. numbers must be an array

dataList = [
 {
  pname: "abc",
  numbers: [123, 234]
 },
{
  pname: "mno",
  numbers: [125,  237]
 }
]

Upvotes: 32

Related Questions