首页 > 解决方案 > Angular MatTable 中没有数据源检测

问题描述

我的数据源有问题,因为我需要在表的标题中显示一个 selectAll 复选框。

当我尝试对 dataSource 进行 console.log 时,它返回一个空数组,而 dataSource.data-length 返回零。

我需要一个输入,因为该组件是另一个组件的子组件


<image-list [imageList]="imageList"></image-list>


我试图把它放在 ngOnit 中,但它不起作用

import { Component, OnInit, Inject, OnDestroy, Input } from "@angular/core";
import { ImageModel } from "../image.model";
import { MatTableDataSource } from '@angular/material';

export class ImageListComponent implements OnInit, OnDestroy {
  
  @Input() imageList: ImageModel[];
  selection = new SelectionModel(true, [], true);
  selectionModelChanged = new BehaviorSubject([]);
  dataSource = new MatTableDataSource();
  row: any;
  

  constructor(private builderService: BuilderService,
    @Inject(DOCUMENT) private document: any) {
    this._unsubscribeAll = new Subject();
    // this.dataSource = new MatTableDataSource(this.imageList); //it won't work here
  }

  ngOnDestroy() {
    this.imageListChange.unsubscribe();
    clearInterval(this.callLoop);
  }

  ngOnInit() {
    this.getImageList();
    this.dataSource = new MatTableDataSource(this.imageList);
    console.log(this.dataSource.data) // returns []
    this.imageListChange = this.builderService.imageRemoved$.subscribe(() => {
      this.getImageList();
    });

        
    
  }

  private getImageList() {
    this.builderService.getFinishedImagesList().then(response => {
      this.imageErrorMessage = null;
      this.imageList = response;
      console.log(response)
    }).catch(() => {
      this.imageErrorMessage = "Oops, there was an error getting the builds list.";
    });
  }

  markAsSelected(device: any): void {
    this.selection.isSelected(device);
}


/** Whether the number of selected elements matches the total number of rows. */
isAllSelected(): boolean {
  let numSelected = null;
  let numRows = null;
      numSelected = this.selectedImages.length;
      numRows = this.dataSource.data.length; //always zero so, select All won't work
  return numSelected === numRows; 
}
 
}

提前感谢您的回复。

标签: angulartypescript

解决方案


我认为您应该在初始化列表时设置一个空数组。

@Input() imageList: ImageModel[] = [];

推荐阅读