【问题标题】:Sort table data with Angular Material使用 Angular Material 对表格数据进行排序
【发布时间】:2019-07-24 08:28:45
【问题描述】:

我已经使用 Angular 和 Material 设置了一个组件。我有想要使用 BitBucket 状态 API 正确公开的数据: https://bitbucket.status.atlassian.com/api#status

我只是停留在如何对列启用排序,我想使用默认设置对所有 3 个进行排序。任何方向将不胜感激。

这是一个堆栈闪电战:https://stackblitz.com/edit/angular-gmdy9j

HTML:

<div class="example-table-container">

    <table mat-table [dataSource]="data"
           matSort matSortActive="name" matSortDirection="desc">


      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header disableClear>Name</th>
        <td mat-cell *matCellDef="let row">{{row.name}}</td>
      </ng-container>


      <ng-container matColumnDef="status">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Status</th>
        <td mat-cell *matCellDef="let row">{{row.status}}</td>
      </ng-container>


      <ng-container matColumnDef="created_at">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>
          Created
        </th>
        <td mat-cell *matCellDef="let row">{{row.created_at | date}}</td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>

  </div>

TS:

import {HttpClient} from '@angular/common/http';
import {Component, ViewChild, AfterViewInit} from '@angular/core';
import {MatSort} from '@angular/material';
import {merge, Observable, of as observableOf} from 'rxjs';
import {catchError, map, startWith, switchMap} from 'rxjs/operators';

@Component({
  selector: 'app-headlines',
  templateUrl: './headlines.component.html',
  styleUrls: ['./headlines.component.scss']
})

export class HeadlinesComponent implements AfterViewInit {
  displayedColumns: string[] = ['name', 'status', 'created_at'];
  tableDatabase: TableHttpDatabase | null;
  data: BitBucketIssue[] = [];

  resultsLength = 0;
  isLoadingResults = true;


  @ViewChild(MatSort) sort: MatSort;

  constructor(private http: HttpClient) {}

  ngAfterViewInit() {
    this.tableDatabase = new TableHttpDatabase(this.http);

    merge(this.sort.sortChange)
      .pipe(
        startWith({}),
        switchMap(() => {
          this.isLoadingResults = true;
          return this.tableDatabase!.getRepoIssues(
            this.sort.active, this.sort.direction);
        }),
        map(data => {

          // Flip flag to show that loading has finished.
          this.isLoadingResults = false;
          this.resultsLength = data.incidents.length;
          console.log(data.incidents.length)
          console.log(data.incidents)
          return data.incidents;

        }),
        catchError(() => {
          this.isLoadingResults = false;
          return observableOf([]);
        })
      ).subscribe(data => this.data = data);
  }
}

export interface BitBucketApi {
  incidents: BitBucketIssue[];
}

export interface BitBucketIssue {
  name: string;
  status: string;
  created_at: number;
}

/** An example database that the data source uses to retrieve data for the table. */
export class TableHttpDatabase {
  constructor(private http: HttpClient) {}

  getRepoIssues(sort: string, order: string): Observable<BitBucketApi> {
    const href = 'https://bqlf8qjztdtr.statuspage.io/api/v2/incidents.json';
    const requestUrl =
        `${href}?q=&sort=${sort}&order=${order}`;

    return this.http.get<BitBucketApi>(requestUrl);
  }
}

这是一个堆栈闪电战:https://stackblitz.com/edit/angular-gmdy9j

【问题讨论】:

    标签: angular typescript angular-material


    【解决方案1】:

    您似乎没有将所需的 MatTableDataSource 链接到您检索到的数据。 您需要将 MatSort 元素分配给 MatTableDataSource 排序属性,并使用 MatTableDataSource 来显示数据。官方文档https://material.angular.io/components/sort/overview

    中都有详细记录

    角码

    import {HttpClient} from '@angular/common/http';
    import {Component, ViewChild, AfterViewInit} from '@angular/core';
    import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';
    import {merge, Observable, of as observableOf} from 'rxjs';
    import {catchError, map, startWith, switchMap} from 'rxjs/operators';
    
    /**
     * @title Table retrieving data through HTTP
     */
    @Component({
      selector: 'table-http-example',
      styleUrls: ['table-http-example.css'],
      templateUrl: 'table-http-example.html',
    })
    export class TableHttpExample implements AfterViewInit {
      displayedColumns: string[] = ['name', 'status', 'created_at'];
      tableDatabase: TableHttpDatabase | null;
      data: BitBucketIssue[] = [];
      dataSource: MatTableDataSource<BitBucketIssue>;
    
      resultsLength = 0;
      isLoadingResults = true;
    
    
      @ViewChild(MatSort) sort: MatSort;
    
      constructor(private http: HttpClient) {}
    
      ngAfterViewInit() {
        this.tableDatabase = new TableHttpDatabase(this.http);
    
        merge(this.sort.sortChange)
          .pipe(
            startWith({}),
            switchMap(() => {
              this.isLoadingResults = true;
              return this.tableDatabase!.getRepoIssues(
                this.sort.active, this.sort.direction);
            }),
            map(data => {
    
              // Flip flag to show that loading has finished.
              this.isLoadingResults = false;
              this.resultsLength = data.incidents.length;
              console.log(data.incidents.length)
              console.log(data.incidents)
              return data.incidents;
    
            }),
            catchError(() => {
              this.isLoadingResults = false;
              return observableOf([]);
            })
          ).subscribe(data => {
            this.data = data; this.dataSource = new MatTableDataSource(data);
            this.dataSource.sort = this.sort;
          });
      }
    }
    
    export interface BitBucketApi {
      incidents: BitBucketIssue[];
    }
    
    export interface BitBucketIssue {
      name: string;
      status: string;
      created_at: number;
    }
    
    /** An example database that the data source uses to retrieve data for the table. */
    export class TableHttpDatabase {
      constructor(private http: HttpClient) {}
    
      getRepoIssues(sort: string, order: string): Observable<BitBucketApi> {
        const href = 'https://bqlf8qjztdtr.statuspage.io/api/v2/incidents.json';
        const requestUrl =
            `${href}?q=&sort=${sort}&order=${order}`;
    
        return this.http.get<BitBucketApi>(requestUrl);
      }
    }
    

    HTML

    <div class="example-table-container">
    
        <table mat-table [dataSource]="dataSource"
               matSort matSortActive="name" matSortDirection="desc">
    
          <!-- Title Column -->
          <ng-container matColumnDef="name">
            <th mat-header-cell *matHeaderCellDef mat-sort-header disableClear>Name</th>
            <td mat-cell *matCellDef="let row">{{row.name}}</td>
          </ng-container>
    
          <!-- State Column -->
          <ng-container matColumnDef="status">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>Status</th>
            <td mat-cell *matCellDef="let row">{{row.status}}</td>
          </ng-container>
    
          <!-- Created Column -->
          <ng-container matColumnDef="created_at">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>
              Created
            </th>
            <td mat-cell *matCellDef="let row">{{row.created_at | date}}</td>
          </ng-container>
    
          <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
          <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
        </table>
    
      </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 2018-03-08
      • 2020-12-15
      相关资源
      最近更新 更多