I´m trying to divide dynamically the table element to it´s own separate columns. My desired output looks like this:
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:
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.
CodePudding user response:
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>