This is my hobby project and it has been stuck due of this issue for some time. It might be an easy issue, but my knowledge about Angular and JS is rather limited.. Nevertheless my code is below (I have shorten it a bit) and it is working to some extent. It is fetching data from server and then it is displayed at client. No issues there, but now when I am trying to do client side filtering then nothing happens. Literally. I am typing into filter input box and nothing. Table rows are not filtered.
I am wondering here two things:
- Do I use right approach (can I extend MatTableDataSource)?
- What I am doing wrong (if I can extend MatTableDataSource)?
MyData.ts
export interface MyData {
id: number;
description: string;
}
MyData.service.ts
export class MyService {
constructor(private http: HttpClient) { }
getData(): Observable<MyData[]> {
return this.http.get...
}
}
MyData.datasource.ts
export class MyDataSource extends MatTableDataSource<MyData> {
private mySubject = new BehaviorSubject<MyData[]>([]);
constructor(private myService: MyService) { super(); }
loadData() {
this.myService.getData()
.pipe(catchError(() => of([])))
.subscribe(data => this.mySubject.next(data));
}
connect(): BehaviorSubject<myData[]> {
return this.mySubject;
}
disconnect(): void {
this.mySubject.complete();
}
}
MyData.component.ts
export class MyDataComponent implements OnInit {
displayedColumns= ["id", "description"];
dataSource: MyDataSource;
constructor(private myService: MyService) { }
ngOnInit() {
this.dataSource = new MyDataSource(this.myService);
this.dataSource.loadData();
}
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
}
MyData.component.html
<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
<mat-table [dataSource]="dataSource">
<ng-container matColumnDef="id">
<mat-header-cell *matHeaderCellDef>ID</mat-header-cell>
<mat-cell *matCellDef="let data">{{data.id}}</mat-cell>
</ng-container>
<ng-container matColumnDef="description">
<mat-header-cell *matHeaderCellDef>Description</mat-header-cell>
<mat-cell *matCellDef="let data">{{data.description}}</mat-cell>
</ng-container>
</mat-table>
this.dataSource.filter
you're firing filtering on inner source – FissileMyDataSource
and callingMyService
directly fromMyComponent
which would return an array of data that I would use to instantiateMatTableDataSource
? – Tonneau