0
votes

I want to list a records in mat-table format. My array of data is as below in this screenshot.

enter image description here

As seen in the image console log it has two records but in table listing it displays only first record.

Here is my component in which i am getting records from the api services. As i am getting records through the array.map() so i am pushing the records into the array variable and have called my function into ngAfterViewInit() life cycle method.

export class RecordComponent implements OnInit, AfterViewInit {
  displayedColumns = ['id', 'name',];
  data = [];
  recordList: any;

  ngOnInit() {
    this.recordList = new MatTableDataSource(this.data);
  }

  ngAfterViewInit() {
    this.getRecordListList();
  }

  getRecordListList() {
    var Arr = []
    this.recordList.data = [];
    this.apiService.getProductId(this.params.id).subscribe((response:any) => {
      let data = response.data[0]
      let productData = data.design_product
      productData.map((productid) => {
        this.apiService.getSelectedProductById(productid.selected_product_id).subscribe((response:any) => {
          if(response.data !== null) {
            Arr.push(response.data[0])
            this.recordList = Arr
            this.data = Arr;
            console.log(this.recordList) // line no 59 as displayed in the screenshot
          }
        })
      })
    })
  }
}

Here is my HTML component.

<mat-table [dataSource]="recordList">
  <ng-container matColumnDef="id">
    <mat-header-cell *matHeaderCellDef >Sr No</mat-header-cell>
    <mat-cell *matCellDef="let element; let i = index"> {{i+1}} </mat-cell>
  </ng-container>
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef >Name</mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
  </ng-container>
  <mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
1

1 Answers

0
votes

try this

if(response.data !== null) { 
  this.data = response.data;
  this.recordList = new MatTableDataSource(this.data);
}