Mat-table 排序演示不起作用

2024-04-23

我正在尝试获取mat-table排序在本地工作,虽然我可以让数据按预期显示,但单击标题行不会像在线示例那样进行排序(根本没有发生任何事情)。 我正在尝试让这个演示在本地运行:https://material.angular.io/components/sort/overview https://material.angular.io/components/sort/overview https://plnkr.co/edit/XF5VxOSEBxMTd9Yb3ZLA?p=preview https://plnkr.co/edit/XF5VxOSEBxMTd9Yb3ZLA?p=preview

我使用 Angular CLI 生成了一个新项目,然后按照以下步骤操作:https://material.angular.io/guide/getting-started https://material.angular.io/guide/getting-started

这是我的本地文件:

应用程序模块.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MatSort, MatTableModule } from '@angular/material';

import { AppComponent } from './app.component';
import { TableSortingExample } from './table-sorting-example';

@NgModule({
  declarations: [
    AppComponent,
    TableSortingExample,
    MatSort
  ],
  imports: [
    BrowserModule,
    MatTableModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

应用程序组件.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

应用程序组件.html

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!
  </h1>
  <table-sorting-example></table-sorting-example>
</div>

表排序示例.html

<div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource" matSort>

    <!--- Note that these columns can be defined in any order.
          The actual rendered columns are set as a property on the row definition" -->

    <!-- ID Column -->
    <ng-container matColumnDef="userId">
      <mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.id}} </mat-cell>
    </ng-container>

    <!-- Progress Column -->
    <ng-container matColumnDef="progress">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Progress </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.progress}}% </mat-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="userName">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
    </ng-container>

    <!-- Color Column -->
    <ng-container matColumnDef="color">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Color </mat-header-cell>
      <mat-cell *matCellDef="let row" [style.color]="row.color"> {{row.color}} </mat-cell>
    </ng-container>

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


<!-- Copyright 2017 Google Inc. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license -->

表排序示例.ts

import {Component, ViewChild} from '@angular/core';
import {DataSource} from '@angular/cdk/collections';
import {MatSort} from '@angular/material';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';

/**
 * @title Table with sorting
 */
@Component({
  selector: 'table-sorting-example',
  styleUrls: ['table-sorting-example.css'],
  templateUrl: 'table-sorting-example.html',
})
export class TableSortingExample {
  displayedColumns = ['userId', 'userName', 'progress', 'color'];
  exampleDatabase = new ExampleDatabase();
  dataSource: ExampleDataSource | null;

  @ViewChild(MatSort) sort: MatSort;

  ngOnInit() {
    this.dataSource = new ExampleDataSource(this.exampleDatabase, this.sort);
  }
}

/** Constants used to fill up our data base. */
const COLORS = ['maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple',
  'fuchsia', 'lime', 'teal', 'aqua', 'blue', 'navy', 'black', 'gray'];
const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',
  'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper',
  'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'];

export interface UserData {
  id: string;
  name: string;
  progress: string;
  color: string;
}

/** An example database that the data source uses to retrieve data for the table. */
export class ExampleDatabase {
  /** Stream that emits whenever the data has been modified. */
  dataChange: BehaviorSubject<UserData[]> = new BehaviorSubject<UserData[]>([]);
  get data(): UserData[] { return this.dataChange.value; }

  constructor() {
    // Fill up the database with 100 users.
    for (let i = 0; i < 100; i++) { this.addUser(); }
  }

  /** Adds a new user to the database. */
  addUser() {
    const copiedData = this.data.slice();
    copiedData.push(this.createNewUser());
    this.dataChange.next(copiedData);
  }

  /** Builds and returns a new User. */
  private createNewUser() {
    const name =
      NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
      NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

    return {
      id: (this.data.length + 1).toString(),
      name: name,
      progress: Math.round(Math.random() * 100).toString(),
      color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
    };
  }
}

/**
 * Data source to provide what data should be rendered in the table. Note that the data source
 * can retrieve its data in any way. In this case, the data source is provided a reference
 * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage
 * the underlying data. Instead, it only needs to take the data and send the table exactly what
 * should be rendered.
 */
export class ExampleDataSource extends DataSource<any> {
  constructor(private _exampleDatabase: ExampleDatabase, private _sort: MatSort) {
    super();
  }

  /** Connect function called by the table to retrieve one stream containing the data to render. */
  connect(): Observable<UserData[]> {
    const displayDataChanges = [
      this._exampleDatabase.dataChange,
      this._sort.sortChange,
    ];

    return Observable.merge(...displayDataChanges).map(() => {
      return this.getSortedData();
    });
  }

  disconnect() {}

  /** Returns a sorted copy of the database data. */
  getSortedData(): UserData[] {
    const data = this._exampleDatabase.data.slice();
    if (!this._sort.active || this._sort.direction == '') { return data; }

    return data.sort((a, b) => {
      let propertyA: number|string = '';
      let propertyB: number|string = '';

      switch (this._sort.active) {
        case 'userId': [propertyA, propertyB] = [a.id, b.id]; break;
        case 'userName': [propertyA, propertyB] = [a.name, b.name]; break;
        case 'progress': [propertyA, propertyB] = [a.progress, b.progress]; break;
        case 'color': [propertyA, propertyB] = [a.color, b.color]; break;
      }

      let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
      let valueB = isNaN(+propertyB) ? propertyB : +propertyB;

      return (valueA < valueB ? -1 : 1) * (this._sort.direction == 'asc' ? 1 : -1);
    });
  }
}


/**  Copyright 2017 Google Inc. All Rights Reserved.
 Use of this source code is governed by an MIT-style license that
 can be found in the LICENSE file at http://angular.io/license */

有谁知道为什么它会像在线表格一样显示但缺乏排序功能?


对于可能遇到此问题的其他人: 问题是我没有正确阅读 Angular Materials 网站上的 API 参考,该部分说我必须导入 MatSortModule。在我更改导入列表后应用程序模块.ts to

imports: [
    BrowserModule,
    MatTableModule,
    MatSortModule
  ],

效果很好

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mat-table 排序演示不起作用 的相关文章

随机推荐

  • FCM flutter 启用通知振动

    我正在为 Android 和 IOS 开发 Flutter 应用程序 我已经根据这个为Android创建了通知渠道article https rechor medium com creating notification channels
  • 类型 x 比值更难访问

    这是我的代码的抽象 module RootModule module private SubModule I want everything in this module to be inaccessible from outside th
  • Heroku 上带有 Django Channels 的 Websocket

    我正在尝试将我的应用程序部署到heroku 该应用程序有一个简单的聊天系统 使用 Websockets 和 django 通道 当我使用 python manage py runserver 测试我的应用程序时 应用程序的行为正如预期的那样
  • 处理时间跨度的最佳方式?

    PHP 中是否有处理时间跨度的首选类或方法 我感兴趣的主要功能是检查日期是否在时间跨度内 或生成下限和上限的时间戳 使用unix时间戳 如果是mysql数据 那么你可以像这样存储时间戳 如果不是 那么你也可以将mysql日期时间转换为uni
  • 如何使表格中一行的最后一个单元格占据所有剩余宽度

    在下面的 HTML 片段中 如何使包含 LAST 的列的宽度占据行的其余部分 并且包含 COLUMN ONE 和 COLUMN TWO 的列的宽度足以包含其内容 并且不更大 谢谢 table border collapse collapse
  • Gorm 中的级联删除不会删除关联表

    我是戈尔姆的新手 我试图进行级联删除 如果我删除一个用户 与该用户关联的角色 属于 个人资料 有一个 和书籍 一对多 也将被删除 我在下面设置了模型 但级联似乎不起作用 当我删除用户时 角色 个人资料和书籍仍保留在数据库中 而不是被删除 软
  • 单击元素以外的任意位置以使用 if 语句隐藏它

    解决方案如下 我已经阅读了这里有关这个概念的大多数问题 但我似乎无法让它与 if 语句一起使用 有什么帮助吗 JSFiddle http jsfiddle net 2udYp button click function div fadeTo
  • 如何通过 Swift 包管理器在 Xcode 中安装包

    我正在 Xcode 中开发一个项目 并尝试安装和使用加密货币Swift https github com krzyzanowskim CryptoSwift通过 Swift 包管理器进行包 我读了文档 https swift org pac
  • CMake:不支持的 GNU 版本 - 不支持高于 8 的 gcc 版本

    在降级我的 GCC 之前 我想知道是否有一种方法可以确定我的机器中的哪些程序 框架或依赖项将被破坏 以及是否有更好的方法来安装 openpose 例如 更改 CMake 中的某些内容 有没有办法可以解决这个问题 而无需更改我的系统 GCC
  • 同时使用 :nth-child 和 :nth-last-child

    我做不到 nth child and nth last child伪类同时工作 效果很好 突出显示前 3 个要素 a li nth child n 3 background fbfcc8 效果很好 突出显示最后 3 个元素 b li nth
  • Android:如何以原始尺寸显示图像

    我从字节数组创建位图图像并将其显示在 ImageView 中 这android layout width and android layout heightImageView 的设置为wrap content 并且android scale
  • 通过属性和正文指定 JSTL 值之间的区别

    我试图弄清楚 JSTL 的这两种用途之间是否存在功能差异
  • 电话号码的 jQuery 输入掩码

    我希望用户的输入自动填充电话号码的标点符号 以便看起来像这样 xxx xxx xxxx 这是我的 HTML 代码 div class form group div
  • UIManagedDocument 迁移数据模型

    我正在开发一个 iPhone 应用程序 它使用UIManagedDocument并将其文档存储在 iCloud 上 一切都工作正常 直到我更改了我的核心数据模型 方案 添加了新的模型版本 就像我在过去几周内多次所做的那样 我添加了一个新属性
  • 如何使用python Bottle框架获取客户端IP地址

    我需要使用 python 的客户端 IP 地址 我已经尝试过下面的代码 但它在服务器中不起作用 from socket import gethostname gethostbyname ip gethostbyname gethostnam
  • 任务并行不稳定,有时使用 100% CPU

    我目前正在测试 C 的 Parallel 一般来说 它工作得很好 并且使用并行比普通的 foreach 循环更快 然而 有时 比如五分之一 我的 CPU 会达到 100 使用率 导致并行任务非常慢 我的 CPU 设置是 i5 4570 和
  • R:评估字符串

    事实证明需要定义一个函数eval string它评估一个字符串 就像它是一个表达式 调用 一样 例如 如果 string lt cyl 6 disp gt 200 我想要 eval string string mtcars 相当于 eval
  • 捕获 json.net 序列化错误

    我正在使用 dotnet core 2 2 开发 Web api 我们希望捕获序列化异常并返回 400 badRequest 以与验证错误 422UnprocessableEntity 区分开 我们尝试创建一个异常处理程序 public v
  • Spring data JPA和hibernate分离实体传递以持久化ManyToMany关系

    我正在尝试保留一个与已保留的其他对象具有多对多关系的对象 这是我的持久化对象 它们已经持久化在数据库中 这是一个 MySql Product Entity Table name PRODUCT public class Product pr
  • Mat-table 排序演示不起作用

    我正在尝试获取mat table排序在本地工作 虽然我可以让数据按预期显示 但单击标题行不会像在线示例那样进行排序 根本没有发生任何事情 我正在尝试让这个演示在本地运行 https material angular io component