I have a mat-table with a custom data source (that implements DataSource
and returns an observable
on connect
), similar to this.
I enabled the search, but my @ViewChild(MatSort, {static: true}) sort: MatSort;
is still undefined.
I do not have any *ngIf
and I also gave some initial data to my custom dataSource
just to test some of the answers from here, but it still does not work:
export class ItemsDataSource implements DataSource<Item>{
private dummyItem: Item = {};
private items: Item[] = [this.dummyItem];
private subject = new BehaviorSubject<Item[]>(this.items);
readonly items$ = this.subject.asObservable();
constructor() {
this.dummyItem.setName(`first`);
this.subject.next(this.items); // Have some initial data
}
connect(collectionViewer: CollectionViewer): Observable<Item[]> {
return this.items$;
}
disconnect(collectionViewer: CollectionViewer): void {
this.subject.complete();
}
// This is used by the items service to add streamed items when they become available
public add(item: Item) {
this.items.push(item);
this.subject.next(this.items);
}
}
export class ItemsComponent implements OnInit {
readonly displayedColumns: string[] = ['name'];
public dataSource: ItemsDataSource;
@ViewChild(MatSort, {static: true}) sort: MatSort;
@ViewChild(MatSort, {static: true}) set matSort(sort: MatSort) {
// `sort` is undefined here
// sort.sortChange.subscribe(() => console.log(`sorting`));
}
constructor(private route: ActivatedRoute, private scanService: ItemsService) {
}
ngOnInit() {
this.route.params.pipe(map(param => param.name)).subscribe(name => {
// The scan service will create the ItemsDataSource the first time it is requested
this.dataSource = this.scanService.dataSource(name);
// `this.sort` is undefined here
// this.sort.sortChange.subscribe(() => console.log(`sorting`));
});
}
ngAfterViewInit() {
// `this.sort` is undefined here
//this.sort.sortChange.subscribe(() => console.log(`sorting`));
}
}
<table id="items" mat-table matSort [dataSource]="dataSource" class="mat-elevation-z2">
<ng-container matColumnDef="name">
<th mat-header-cell mat-sort-header *matHeaderCellDef> NAME </th>
<td mat-cell *matCellDef="let item"> {{item.getName()}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
I am kind of stuck, any ideas?