Reputation: 567
This should be basic stuff but somehow Im struggling
table.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent implements OnInit {
tableTitle = 'Table';
tableHeaders = [
'Project',
'Budget',
'Status',
'Users',
'Completion',
'Actions'
];
constructor() { }
ngOnInit(): void {
}
}
table.component.html
<table class="table align-items-center table-flush">
<thead class="thead-light">
<tr *ngFor="let header of tableHeaders">
<th scope="col">{{header}}</th>
</tr>
</thead>
....
is not showing anything....I tried to add the headers with some static values like <th scope="col"> Hello world </th>
and works fine....also tried to print something like this
<table class="table align-items-center table-flush">
<thead class="thead-light">
<tr>
<th scope="col">{{tableHeaders[0]}}</th>
<th scope="col">{{tableHeaders[1]}}</th>
<th scope="col">{{tableHeaders[2]}}</th>
</tr>
</thead>
and again works fine so the var is present in the html.....but when trying it to put it through the *ngFor it doesn't show anything...what am I doing wrong?
Upvotes: 0
Views: 968
Reputation: 387
The implementation of *ngFor in component.html file is not right. *ngFor doesn't work with tr
.
You must have to use *ngFor on th
for creating multiple th
instead of tr
.
<table class="table align-items-center table-flush">
<thead class="thead-light">
<tr>
<th scope="col" *ngFor="let header of tableHeaders">{{header}}</th>
</tr>
</thead>
</table>
Hopefully it works for you in much better way. Thanks
Upvotes: 0
Reputation: 15499
The table.component.html code you are using has the repeat (*ngFor) on the wrong element - you are creating multiple tr's - each with one th.
You should have the *ngFor on the th
to create multiple th's
within the one tr of the thead.
<table class="table align-items-center table-flush">
<thead class="thead-light">
<tr>
<th scope="col" *ngFor="let header of tableHeaders">{{header}}</th>
</tr>
</thead>
</table>
I have added a stackblitz https://stackblitz.com/edit/angular-3eevgn - thank you to @Oussail for the blitz- I modified the code to suit from that original :)
Upvotes: 2