Issue
I'm trying to create a table with information returned from a service. The problem is that the only row shown is the last one in the list returned by the service.
Code from list.component.ts
import { Component, OnInit } from '@angular/core';
import { DepartamentoService } from '../../_service/departamento.service';
export interface Items{
idItem: number;
nameItem: string;
}
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class LoginComponent implements OnInit {
displayedColumns: string[] = ['idItem', 'nameItem', 'options'];
columnsToDisplay: string[] = this.displayedColumns.slice();
itemList: Items[];
constructor(private itemService: ItemsService) { }
ngOnInit(): void {
this.itemService.list().subscribe(data => {
data.forEach(element => {
this.itemList = [{idItem: element.idItem, nameItem: element.nameItem}];
console.log(`Id: ${element.idItem} - Name ${element.nameItem}`);
});
});
}
}
Code from list.component.html
<table mat-table [dataSource]="itemList" class="mat-elevation-z8">
<ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
<th id="head" mat-header-cell *matHeaderCellDef> {{column}} </th>
<td mat-cell *matCellDef="let element"> {{element[column]}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
<tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</table>
Any help is appreciated.
Solution
You are assigning the value in the wrong way to the itemList variable. You're doing:
this.itemList = [{idItem: element.idItem, nameItem: element.nameItem}];
What's wrong with this is that every iteration of the loop you're re-assigning only one row to the itemList variable, you need to push each a value each iteration in order to show all of the rows.
You need to do this:
this.itemList.push({idItem: element.idItem, nameItem: element.nameItem};
Be sure to declare item list this way:
itemList: any[] = []; // add a empty array as first value to be able to use the push() method
Answered By - Angel Rivas Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.