angular - 在Angular中对表格列进行排序

标签 angular typescript

我正在尝试使我的表格列可排序。我在这里找到了这个教程:https://www.youtube.com/watch?v=UzRuerCoZ1E&t=715s
使用这些信息,我得到了以下结果:
处理排序的管道

import { Pipe, PipeTransform } from '@angular/core';

    @Pipe({
      name: 'sort',
      pure: true
    })
    export class TableSortPipe implements PipeTransform {
    
      transform(list: any[], column:string): any[] {
          let sortedArray = list.sort((a,b)=>{
            if(a[column] > b[column]){
              return 1;
            }
            if(a[column] < b[column]){
              return -1;
            }
            return 0;
          })
        return sortedArray;
      }
    
    }
这是帮助我构建表格的组件。这里我定义了 sortedColumn 变量。
import { NavbarService } from './../navbar/navbar.service';
import { LiveUpdatesService } from './live-updates.service';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-live-updates',
  templateUrl: './live-updates.component.html',
  styleUrls: ['./sass/live-updates.component.scss']
})
export class LiveUpdatesComponent implements OnInit{
  stocks$: Observable<any[]>;
  sortedColumn: string;

  constructor(private updatesService: LiveUpdatesService, public nav: NavbarService) {
    this.stocks$ = this.updatesService.getStocks();
  }

  ngOnInit() {
    this.nav.show();
  }
}
这是我的模板文件。如您所见,我附上了我的sort管道到我的循环,吐出表格行。值得注意的是,我渲染表格的方式与视频不同。例如,他的数据存储在数组中,但我的数据存储在 Firebase 上。他正在动态渲染他的表格,但我的表格固定在一定数量的列上。我也在对标题进行硬编码,但他使用他的数组中的变量名来生成表标题。我不确定这些差异是否会阻止事情正常进行。
<section class="score-cards">
    <app-score-cards></app-score-cards>
</section>
<section class="live-updates-wrapper">
    <div class="table-wrapper">
        <table class="stock-updates">
            <thead>
                <tr>
                    <th class="ticker-fixed">Ticker</th>
                    <th><a (click)="sortedColumn = $any($event.target).textContent">Ask Price</a></th>
                    <th><a (click)="sortedColumn = $any($event.target).textContent">Tax Value</a></th>
                    <th><a (click)="sortedColumn = $any($event.target).textContent">Est. Value</a></th>
                    <th><a (click)="sortedColumn = $any($event.target).textContent">Location</a></th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let s of stocks$ | async | sort : sortedColumn">
                    <td class="ticker-fixed">
                        <a target="_blank" href="https://robinhood.com/stocks/{{ s.TICKER }}">{{ s.TICKER }}</a>
                        <span class="sp500">{{ s.sp500_flag }}S&P</span>
                    </td>
                    <td>{{ s.CLOSE }}</td>
                    <td>{{ s.tax_diff }}</td>
                    <td>{{ s.MarketCap }}</td>
                    <td>{{ s.Sector }}</td>
                </tr>
            </tbody>
        </table>
    </div>
</section>
我在下面收到以下错误,但能够通过在我的管道文件中注入(inject)以下代码来修复它:list = !!list ? list : [];现在没有错误,但排序没有按预期工作。当我单击表头时,什么也没有发生。我怎样才能解决这个问题?
enter image description here

最佳答案

忘记管道。通过管道进行排序是不好的做法,会导致错误的代码或糟糕的性能。
改用 observables。
首先更改模板标题按钮以调用函数,并确保您提供要排序的实际属性名称,而不是标题内容:

<th><a (click)="sortOn('CLOSE')">Ask Price</a></th>
<th><a (click)="sortOn('tax_diff')">Tax Value</a></th>
<th><a (click)="sortOn('MarketCap')">Est. Value</a></th>
<th><a (click)="sortOn('Sector')">Location</a></th>
然后,拉出您的排序功能并导入到您的组件中:
  export function sortByColumn(list: any[] | undefined, column:string, direction = 'desc'): any[] {
      let sortedArray = (list || []).sort((a,b)=>{
        if(a[column] > b[column]){
          return (direction === 'desc') ? 1 : -1;
        }
        if(a[column] < b[column]){
          return (direction === 'desc') ? -1 : 1;
        }
        return 0;
      })
    return sortedArray;
  }
然后修复你的组件:
// rx imports
import { combineLatest, BehaviorSubject } from 'rxjs';
import { map, scan } from 'rxjs/operators';

...

export class LiveUpdatesComponent implements OnInit{
  stocks$: Observable<any[]>;
  // make this a behavior subject instead
  sortedColumn$ = new BehaviorSubject<string>('');
  
  // the scan operator will let you keep track of the sort direction
  sortDirection$ = this.sortedColumn$.pipe(
    scan<string, {col: string, dir: string}>((sort, val) => {
      return sort.col === val
        ? { col: val, dir: sort.dir === 'desc' ? 'asc' : 'desc' }
        : { col: val, dir: 'desc' }
    }, {dir: 'desc', col: ''})
  )

  constructor(private updatesService: LiveUpdatesService, public nav: NavbarService) {
    // combine observables, use map operator to sort
    this.stocks$ = combineLatest(this.updatesService.getStocks(), this.sortDirection$).pipe(
      map(([list, sort]) => !sort.col ? list : sortByColumn(list, sort.col, sort.dir))
    );
  }

  // add this function to trigger subject
  sortOn(column: string) {
    this.sortedColumn$.next(column);
  }

  ngOnInit() {
    this.nav.show();
  }
}
最后,修复你的 ngFor :
<tr *ngFor="let s of stocks$ | async">
这样,您就不会依赖魔术或更改检测。当需要通过可观察对象触发时,您正在触发您的排序

关于angular - 在Angular中对表格列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63601301/

相关文章:

angular - 单击添加类和删除切换类

visual-studio-2013 - 如何在 Visual Studio 中将 TypeScript 输出合并到多个文件中

angular - 如何修复 Angular 'source.lift is not a function' 错误?

css - Angular - Material : Progressbar custom color?

css - Angular:primeng 的样式无法工作,即使它们列在 styles.scss 中

reactjs - 如何在 useEffect 中向 useRef 添加事件监听器

javascript - 在 angular-archwizard 步骤上更改边框颜色

Angular `<router-outlet>` 显示模板两次

typescript [数字,数字]与数字[]

typescript - 类型 'x' 上不存在属性 'never'