Daniel
Daniel

Reputation: 311

How to fill a table with data from service in Angular Material?

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.

Upvotes: 0

Views: 3199

Answers (3)

Daniel
Daniel

Reputation: 311

The information provided in the answers works, but I had to add another step:

export class LoginComponent implements OnInit {

 displayedColumns: string[] = ['idItem', 'nameItem', 'options'];
 columnsToDisplay: string[] = this.displayedColumns.slice();
 itemList: Items[];
 dataSource = []; // create a new array
 
 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}`);
     });
     this.dataSource = this.itemList; // assign the array with the data to the new one
 });
}

You must change the source of the data in the table with the name of the new array:

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

Upvotes: 0

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17600

Example Firstly I saw here

 displayedColumns: string[] = ['idItem', 'name', 'options'];

and Items interface is ummatched. change name to nameItem

 displayedColumns: string[] = ['idItem', 'nameItem', 'options'];

another part is that you need to push it rather that assign

this.itemList.push({idItem: element.idItem, nameItem: element.nameItem};

and don't forget to initialize your itemList in constructor or ngOnInit life cycle.

this.itemList=[];

Upvotes: 1

Angel Rivas
Angel Rivas

Reputation: 11

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

Upvotes: 1

Related Questions