【问题标题】:Is it possible to sort tiles in a grid-list?是否可以对网格列表中的图块进行排序?
【发布时间】:2019-11-14 12:47:45
【问题描述】:

我遇到了以下问题:我有一个名为“scenario”的类,它有几个属性,如“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)));

【问题讨论】:

  • 这可能会帮助你Link

标签: angular typescript sorting


【解决方案1】:

在发送到模板之前,您应该按属性对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 会在任何这些 Observables 发生变化时发出,而在 map 中,您只需对列表进行排序。

当您想更改排序顺序时,只需调用:

sortProperty$.next('nowSortByThisProperty');

最后在模板中列出来自filteredSortedScenarios$ 的场景:

<mat-grid-tile *ngFor="let scenario of filteredSortedScenarios$ | async ">

【讨论】:

  • 您好,谢谢您的回复。我编辑了我以前的帖子并添加了一些信息。此外,我犯了一个错误,它不是javascript,而是打字稿……对不起,我的错。因为我需要显示通过搜索过滤的场景和排序顺序,所以我不能只使用 ngFor="let 过滤SortedScenarios$ 的场景。对不起,我对角度和前端开发完全陌生。感谢任何帮助评论。谢谢
猜你喜欢
  • 2018-01-18
  • 2019-09-26
  • 2013-09-04
  • 2018-04-20
  • 2010-10-15
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多