【问题标题】:Angular 6: mat-table [dataSource] renders only first record from data arrayAngular 6:mat-table [dataSource] 仅呈现数据数组中的第一条记录
【发布时间】:2020-08-04 01:37:23
【问题描述】:

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

从图像控制台日志中可以看出,它有两条记录,但在列表中它只显示第一条记录。

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

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 组件。

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

【问题讨论】:

    标签: angular angular-material mat-table


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 那不行……已经在ngOnInit()生命周期方法中声明了这个。
    • 好的,您可以删除该行。你在 this.data 中得到了什么?
    • 请查看问题描述中的屏幕截图,我得到的相同记录是this.data
    • 虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,纯代码的答案没有用处。
    • @Mustafa:你能解释一下你到底在说什么吗?我不明白你的意思。
    猜你喜欢
    • 2020-02-01
    • 2018-11-13
    • 1970-01-01
    • 2018-12-24
    • 2021-07-11
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多