Reputation: 139
I have a problem with the datasource as I need to display a selectAll checkbox in the header of the table.
When I try to console.log the dataSource it returns an empty array, and dataSource.data-length returns zero.
I need an Input because the component is child of another component
<image-list [imageList]="imageList"></image-list>
I tried to put it in the ngOnit, but it doesn't work
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;
}
}
Thanks in advance for your response.
Upvotes: 2
Views: 207
Reputation: 7650
I think you should set an empty array when initializing the list.
@Input() imageList: ImageModel[] = [];
Upvotes: 5