Search code examples
angularangular-ng-ifangular13angular-ngforangular-load-children

Cannot do ng for loop binding in angular 13


I would like to do an angular 13 looping to split data to one column when duplicate entries came from database

now I got like this enter image description here

I Want like this

enter image description here

<table class="custom-table">
<thead>
<tr>
<td colspan="2">&nbsp;</td>
<th colspan="3" scope="colgroup" class="text-center">{{'JobAllowanceperMonth.JobAllowanceperMonth' |
translate}}</th>
 </tr>
  <tr>
<th scope="col">{{ 'Organization.Organization' |
translate}}</th>
<th scope="col">{{ 'AttendancebenifitperDay.AttendancebenifitperDay' |
 translate}}</th>
 <th scope="col">{{ 'Step01.Step01' |
 translate}}</th>
 <th scope="col">{{ 'Step02.Step02' |
  translate}}</th>
 <th scope="col">{{ 'Step03.Step03' |
translate}}</th>                    
  </tr>
 </thead>
    <tbody *ngFor="let salaryVUGDetails of VUGSalaryDetails">
       <tr>
      <th scope="col">{{salaryVUGDetails.OrganisationName}}</th>
        <td>00,000</td>
         <td>{{salaryVUGDetails.Step1}}</td>
          <td>{{salaryVUGDetails.Step2}}</td>
        <td>{{salaryVUGDetails.Step3}}</td>
    </tr>
     </tbody>
  </table>

Solution

  • You can also add a new property "rowspan" to your data to use in .html [attr.rowspan]. For this, first create a new array transform your original "VUGSalaryDetails" adding a new property rowspan

    dataFormated = this.VUGSalaryDetails.map((x, i) => ({
        ...x,
        rowspan:
          i == 0 ||
          this.VUGSalaryDetails[i - 1].OrganizationName != x.OrganizationName
            ? this.VUGSalaryDetails.filter(
                (f) => f.OrganizationName == x.OrganizationName
              ).length
            : -1,
      }));
    

    Then you can use some like

      <tbody>
        <tr *ngFor="let salaryVUGDetails of dataFormated">
          <td
            mat-cell
            *ngIf="salaryVUGDetails.rowspan != -1"
            [attr.rowspan]="
              salaryVUGDetails.rowspan > 0 ? salaryVUGDetails.rowspan : null
            "
          >
            {{ salaryVUGDetails.OrganizationName }}
          </td>
          <td>{{ salaryVUGDetails.Step1 }}</td>
          <td>{{ salaryVUGDetails.Step2 }}</td>
          <td>{{ salaryVUGDetails.Step3 }}</td>
        </tr>
      </tbody>
    

    A stackblitz