Angular 6: mat-table [dataSource] renders only first record from data array

£可爱£侵袭症+ 提交于 2020-04-30 06:33:22

问题


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

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:


try this

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


来源:https://stackoverflow.com/questions/61341301/angular-6-mat-table-datasource-renders-only-first-record-from-data-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!