Angular 6:mat-table [dataSource]仅呈现数据数组中的第一条记录 [英] Angular 6: mat-table [dataSource] renders only first record from data array

查看:79
本文介绍了Angular 6:mat-table [dataSource]仅呈现数据数组中的第一条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以mat-table格式列出记录.我的数据数组如下图所示.

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.

这是我从api服务获取记录的组件.当我通过array.map()获取记录时,我将记录推送到数组变量中,并已将我的函数调用到ngAfterViewInit()生命周期方法中.

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
          }
        })
      })
    })
  }
}

这是我的HTML组件.

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>

推荐答案

尝试一下

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

这篇关于Angular 6:mat-table [dataSource]仅呈现数据数组中的第一条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆