Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular – divide td tag into separate columns dynamically

I´m trying to divide dynamically the table element to it´s own separate columns. My desired output looks like this: enter image description here

Value for name and surname is always 1, but values for subjects and grade are dynamic (there can be 2 columns or more).

This is my data:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data = [
    {
      student: 'Student 1',
      name: 'Alex',
      surname: 'Smith',
      subjects: ['Math','Geometry'],
      grade: ['A','B'],
    },
    {
      student: 'Student 2',
      name: 'Michael',
      surname: 'Laurent',
      subjects: ['Math','Geometry'],
      grade: ['B','C'],
    },
    {
      student: 'Student 3',
      name: 'Sophie',
      surname: 'Miller',
      subjects: ['Math','Geometry','English'],
      grade: ['A','A','B'],
    },
  ];

HTML:

<table>
  <thead>
     <tr>
        <th></th>
        <th *ngFor="let column of data">{{ column.student }}</th>
     </tr>
  </thead>
  <tbody>
     <tr *ngFor="let row of rows">
         <th>{{ row.charAt(0).toUpperCase() + row.slice(1) }}</th>
         <td *ngFor="let item of data">{{ item[row] }}</td>
     </tr>
  </tbody>
</table>

Here is a stackblitz example: https://stackblitz.com/edit/angular-pzgohu
Does anybody know what could be solution? I tried to put span inside td tag and loop through the .length, but it works wrong when I put length on string.

>Solution :

You can either use condition based on row value or you can use typeof to check if it is a string or array https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

<table>
  <thead>
    <tr>
      <th></th>
      <th *ngFor="let column of data">{{ column.student }}</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let row of rows">
      <th>{{ row.charAt(0).toUpperCase() + row.slice(1) }}</th>
      <td *ngFor="let item of data">
        <span *ngIf="row !== 'subjects' && row !== 'grade'">
          {{ item[row] }}
        </span>

        <table *ngIf="row === 'subjects' || row === 'grade'">
          <tr>
            <td *ngFor="let subItem of item[row]">
              {{ subItem }}
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </tbody>
</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading