typescript - Ingen datakällupptäckt i Angular MatTable


Jag har ett problem med datakällan eftersom jag behöver visa en väljAlla-checkbox i tabellens rubrik.

När jag försöker console.log dataSource returnerar det en tom array, och dataSource.data-length returnerar noll.

Jag behöver en Input eftersom komponenten är ett barn till en annan komponent

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


Jag försökte sätta det i ngOnit, men det fungerar inte

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

Tack på förhand för ditt svar.

Svar #1

Jag tycker att du ska sätta en tom array när du initierar listan.

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