Issue
So I have a dataSource for my material table that I get externally, and one of my filter fields needs to take unique values from one of the attributes of the objects, and I think the best way to get refreshed data on subsequent 'refresh' calls for the data would be to use a subscription. However since I couldn't for the life of me figure out how to subscribe to a MatTableDataSource
, I went with using of().subscribe()
from rxjs. However, as soon as the table launches, the sub fires off once (since it assigns the initial values to the <mat-select>
options), but none of the subsequent data changes fired it, I looked at the angular dev tools and it turns out that the subscription is closed and stopped
uniqueSubscription :
_finalizers: null
_parentage: null
closed: true
destination: null
initialTeardown: undefined
isStopped: true
so I'm at a loss on how to proceed to have the <mat-select>
options get refreshed whenever new data comes in.
<mat-select class="filterMultiselect"
formControlName="filterParam3"
multiple
panelClass="filterMultiselect"
placeholder="Filter"
(selectionChange)="updateManualPage(1)">
<mat-option *ngFor="let option of dropdownMultipleUniqueOptions"
[value]="option">
{{option}}
</mat-option>
</mat-select>
tableDataSource: MatTableDataSource<randomInterface> = new MatTableDataSource<randomInterface>();
uniqueSubscription: Subscription = new Subscription;
dropdownMultipleUniqueOptions: string[] = [];
ngOnInit() {
this.uniqueSubscription = of(this.tableDataSource.data).subscribe(() => {
this.dropdownMultipleUniqueOptions = this.tableDataSource.data.map(data => data.param3).filter((data, index, array) => array.indexOf(data) === index);
})
}
Solution
Problem is that the of() operator completes immediately afterwards. As already mentioned by @Matthieu Riegler and @TotallyNewb. See also explanation: https://rxjs.dev/api/index/function/of
Here is another approach:
Use connect() method to get a Observable of the DataSource: https://material.angular.io/components/table/overview#datasource and then:
tableDataSource: MatTableDataSource<randomInterface> = new MatTableDataSource<randomInterface>();
dropdownMultipleUniqueOptions$: Observable<string[]>;
ngOnInit() {
this.dropdownMultipleUniqueOptions$ = this.tableDataSource.connect().pipe(
map((data) => {
return data.map(data => data.param3).filter((data, index, array) => array.indexOf(data) === index);
})
}
<mat-select class="filterMultiselect"
formControlName="filterParam3"
multiple
panelClass="filterMultiselect"
placeholder="Filter"
(selectionChange)="updateManualPage(1)">
<mat-option *ngFor="let option of dropdownMultipleUniqueOptions$ | async"
[value]="option">
{{option}}
</mat-option>
</mat-select>
Answered By - oksd
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.