我遇到了以下问题:我有一个名为“方案”的类,具有一些属性,例如“ id”,“ name”,“ number”等。
在html中,场景显示如下:
<mat-grid-list [cols]="breakpoint" rowHeight="4:4" [@gridAnimation]="(scenarios$ | async)?.length" (window:resize)="onResize($event)">
<mat-grid-tile *ngFor="let scenario of filteredScenarios$ | async ">
<app-scenario-card [scenario]="scenario" [routerLink]="['/scenario', scenario.id]"></app-scenario-card>
</mat-grid-tile>
</mat-grid-list>
是否可以通过所选属性(名称,ID,数字...)对显示的场景图块进行排序?我发现的有关排序的所有内容都与表或网格有关。
在可能的情况下,有人可以举一个例子说明如何至少有一种方法吗?
非常感谢您。
顺便说一句,我不能只从网格列表更改为表格。
场景的类具有以下属性:
export class Scenario {
id: number;
scenarioName: string;
scenarioDescription: string;
periods: number; }
我有一个用于过滤的搜索框(类似于本教程的构建-> https://blog.angulartraining.com/dynamic-filtering-with-rxjs-and-angular-forms-a-tutorial-6daa3c44076a)。现在,我只需要一个用于id,scenarioName和句点的排序函数,例如每个Button或DropDown。
用于过滤的代码如下:
this.scenarios$ = this.scenariosService.getScenarios();
this.filter = new FormControl('');
this.filter$ = this.filter.valueChanges.pipe(startWith(''));
this.filteredScenarios$ = combineLatest(this.scenarios$, this.filter$).pipe(
map(([Scenario, filterString]) => Scenario.filter(scenario => scenario.scenarioName.indexOf(filterString) !== -1)));
答案 0 :(得分:0)
在发送到模板之前,应按属性对filteredScenarios$
进行排序。为此,我将介绍另一个具有排序属性的BehaviorSubject
。
很难写,因为您没有发布对象结构但会尝试。
在ts中:
private sortProperty$ = new BehaviorSubject<string>('name'); //or whatever you default sort is
filteredSortedScenarios$: Observable<Scenario>
以及在构造函数或ngOnInt
中:
this.filteredSortedScenarios$ = combineLatest([this.filteredScenarios$, this.sortProperty$])
.pipe(
map(([scenarios, sortBy]) => {
console.log('Sorting by', sortBy);
return scenarios.sort((a, b) => {
switch (sortBy) {
case 'name':
return a.name.localeCompare(b.name);
case 'otherProperty':
return ...;
}
});
}));
combineLatest
会在任何这些“可观察对象”发生更改时发出,并且您只需在map
中对列表进行排序即可。
要更改排序顺序,只需致电:
sortProperty$.next('nowSortByThisProperty');
最后在模板中列出filteredSortedScenarios$
中的方案:
<mat-grid-tile *ngFor="let scenario of filteredSortedScenarios$ | async ">