我有一个带有自定义数据源的垫子表(实现DataSource
并在observable
上返回connect
),类似于this。
我启用了搜索功能,但是我的@ViewChild(MatSort, {static: true}) sort: MatSort;
仍未定义。
我没有任何*ngIf
,我还为自定义dataSource
提供了一些初始数据,只是为了测试here的一些答案,但仍然无法正常工作:
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>
我有点困惑,有什么想法吗?