Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic rowspan in angular

Tags:

html

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.

like image 209
ranjeet8082 Avatar asked Nov 21 '18 06:11

ranjeet8082


3 Answers

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]
 }
]
like image 188
Nandita Sharma Avatar answered Oct 17 '22 09:10

Nandita Sharma


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

like image 27
kohashi Avatar answered Oct 17 '22 08:10

kohashi


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>
like image 1
Yasser Bazrforoosh Avatar answered Oct 17 '22 08:10

Yasser Bazrforoosh