Last active
July 5, 2019 09:53
-
-
Save moniuch/4db830af893e8a5a85883430d9d542fd to your computer and use it in GitHub Desktop.
Struggling with filtering on an ngrx-store sourced MatTable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I don't want to unwrap store observables, but looks like there is no other way | |
export class PageComponent { | |
columnsToDisplay = ['firstName', 'lastName']; | |
students$: Observable<Student[]>; | |
studentsDataSource$: Observable<MatTableDataSource<Student>>; | |
filterCtrl = new FormControl(''); | |
// this works, but performance-wise is doubtful | |
ngOnInit() { | |
this.students$ = this.store.select(fromStudents.getStudents); | |
this.studentsDataSource$ = combineLatest( | |
this.filterCtrl.valueChanges, | |
this.students$, | |
).pipe( | |
map(([term, students]) => { | |
const ds = new MatTableDataSource(students); // <-- this doesn't look efficient - you should onl | |
ds.filter = term.toLowerCase(); | |
console.log(ds); | |
return ds; | |
}) | |
); | |
this.store.dispatch(new studentsActions.LoadStudentsAction()); | |
} | |
// this does not work | |
ngOnInit_v2 { | |
this.students$ = this.store.select(fromStudents.getStudents); | |
this.studentsDataSource$ = this.students$.pipe( | |
map(students => new MatTableDataSource(students)), | |
); | |
this.filterCtrl.valueChanges.pipe( | |
withLatestFrom( | |
this.studentsDataSource$, | |
), | |
).subscribe(([term, ds]) => { | |
ds.filter = term.toLowerCase(); | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<mat-form-field> | |
<input matInput type="text" #studentsFilter [formControl]="filterCtrl" placeholder="Filter"> | |
</mat-form-field> | |
<mat-table [dataSource]="studentsDataSource$ | async" #studentsTable> | |
<ng-container matColumnDef="firstName"> | |
<mat-header-cell *matHeaderCellDef>First Name</mat-header-cell> | |
<mat-cell *matCellDef="let student">{{student.first_name}}</mat-cell> | |
</ng-container> | |
<ng-container matColumnDef="lastName"> | |
<mat-header-cell *matHeaderCellDef>Last Name</mat-header-cell> | |
<mat-cell *matCellDef="let student">{{student.last_name}}</mat-cell> | |
</ng-container> | |
<mat-header-row *matHeaderRowDef="columnsToDisplay; sticky: true"></mat-header-row> | |
<mat-row *matRowDef="let row; columns: columnsToDisplay"></mat-row> | |
</mat-table> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment