垫表排序演示不起作用 [英] Mat-table Sorting Demo not Working
问题描述
我试图让 mat-table
排序在本地工作,虽然我可以让数据按预期显示,但单击标题行不会像它那样进行排序在在线示例上(根本没有发生任何事情).我试图让这个演示在本地工作:https://material.angular.io/components/sort/overviewhttps://plnkr.co/edit/XF5VxOSEBxMTd9Yb3ZLA?p=preview
我使用 Angular CLI 生成了一个新项目,然后按照以下步骤操作:https://material.angular.io/guide/getting-started
这是我的本地文件:
app.module.ts
import { BrowserModule } from '@angular/platform-browser';从'@angular/core' 导入 { NgModule };从'@angular/material' 导入 { MatSort, MatTableModule };从 './app.component' 导入 { AppComponent };import { TableSortingExample } from './table-sorting-example';@NgModule({声明: [应用组件,表排序示例,垫排序],进口:[浏览器模块,垫表模块],提供者:[],引导程序:[AppComponent]})导出类 AppModule { }
app.component.ts
import { Component } from '@angular/core';@成分({选择器:'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']})导出类 AppComponent {标题 = '应用';}
app.component.html
<h1>欢迎来到{{title}}!<table-sorting-example></table-sorting-example>
table-sorting-example.html
<mat-table #table [dataSource]="dataSource" matSort><!--- 请注意,这些列可以按任何顺序定义.实际呈现的列被设置为行定义上的属性" --><!-- ID 列--><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-容器><!-- 进度栏--><ng-container matColumnDef="progress"><mat-header-cell *matHeaderCellDef mat-sort-header>进度 </mat-header-cell><mat-cell *matCellDef="let row">{{row.progress}}% </mat-cell></ng-容器><!-- 名称列--><ng-container matColumnDef="userName"><mat-header-cell *matHeaderCellDef mat-sort-header>名称</mat-header-cell><mat-cell *matCellDef="let row">{{row.name}} </mat-cell></ng-容器><!-- 颜色列--><ng-container matColumnDef="color"><mat-header-cell *matHeaderCellDef mat-sort-header>颜色</mat-header-cell><mat-cell *matCellDef="let row" [style.color]="row.color">{{row.color}} </mat-cell></ng-容器><mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row><mat-row *matRowDef="let row; columns:displayedColumns;"></mat-row></mat-table><!-- 版权所有 2017 Google Inc.保留所有权利.此源代码的使用受 MIT 风格的许可证管理,该许可证可以在 http://angular.io/license --> 的 LICENSE 文件中找到.
table-sorting-example.ts
import {Component, ViewChild} from '@angular/core';从@angular/cdk/collections"导入{DataSource};从@angular/material"导入{MatSort};从 'rxjs/BehaviorSubject' 导入 {BehaviorSubject};从 'rxjs/Observable' 导入 {Observable};导入 'rxjs/add/operator/startWith';导入 'rxjs/add/observable/merge';导入 'rxjs/add/operator/map';/*** @title 表排序*/@成分({选择器:'表排序示例',styleUrls: ['table-sorting-example.css'],templateUrl: 'table-sorting-example.html',})导出类 TableSortingExample {displayColumns = ['userId', 'userName', 'progress', 'color'];exampleDatabase = new ExampleDatabase();数据源:ExampleDataSource |空值;@ViewChild(MatSort) 排序:MatSort;ngOnInit() {this.dataSource = new ExampleDataSource(this.exampleDatabase, this.sort);}}/** 用于填充我们数据库的常量.*/const COLORS = ['栗色'、'红色'、'橙色'、'黄色'、'橄榄色'、'绿色'、'紫色'、'紫红色'、'石灰'、'蓝绿色'、'浅绿色'、'蓝色'、'海军'、'黑色'、'灰色'];const NAMES = ['Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack',夏洛特"、西奥多"、艾拉"、奥利弗"、伊莎贝拉"、贾斯珀"、科拉"、利维"、紫罗兰"、亚瑟"、米娅"、托马斯"、伊丽莎白"];导出接口 UserData {id:字符串;名称:字符串;进度:字符串;颜色:字符串;}/** 数据源用于检索表数据的示例数据库.*/导出类 ExampleDatabase {/** 每当数据被修改时发出的流.*/dataChange: BehaviorSubject= new BehaviorSubject([]);get data(): UserData[] { return this.dataChange.value;}构造函数(){//用 100 个用户填充数据库.for (let i = 0; i <100; i++) { this.addUser();}}/** 向数据库添加一个新用户.*/添加用户() {const CopyData = this.data.slice();copyData.push(this.createNewUser());this.dataChange.next(copyedData);}/** 构建并返回一个新用户.*/私人创建新用户(){常量名称 =NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';返回 {id: (this.data.length + 1).toString(),姓名:姓名,进度:Math.round(Math.random() * 100).toString(),颜色:颜色[Math.round(Math.random() * (COLORS.length - 1))]};}}/*** 数据源提供应在表中呈现的数据.注意数据源* 可以以任何方式检索其数据.在这种情况下,数据源提供了一个参考* 到一个公共数据库,ExampleDatabase.管理数据源不是数据源的责任* 基础数据.相反,它只需要获取数据并将表发送到* 应该被渲染.*/导出类 ExampleDataSource 扩展了 DataSource{构造函数(私有_exampleDatabase:ExampleDatabase,私有_sort:MatSort){极好的();}/** 表调用的连接函数以检索包含要呈现的数据的流.*/connect(): Observable{const displayDataChanges = [this._exampleDatabase.dataChange,this._sort.sortChange,];return Observable.merge(...displayDataChanges).map(() => {返回 this.getSortedData();});}断开连接(){}/** 返回数据库数据的排序副本.*/getSortedData(): UserData[] {const data = this._exampleDatabase.data.slice();if (!this._sort.active || this._sort.direction == '') { 返回数据;}返回 data.sort((a, b) => {让 propertyA: number|string = '';让 propertyB: number|string = '';开关(this._sort.active){case 'userId': [propertyA, propertyB] = [a.id, b.id];休息;case 'userName': [propertyA, propertyB] = [a.name, b.name];休息;case 'progress': [propertyA, propertyB] = [a.progress, b.progress];休息;case 'color': [propertyA, propertyB] = [a.color, b.color];休息;}让 valueA = isNaN(+propertyA) ?属性A:+属性A;让 valueB = isNaN(+propertyB) ?属性B:+属性B;return (valueA < valueB ? -1 : 1) * (this._sort.direction == 'asc' ? 1 : -1);});}}/** 版权所有 2017 Google Inc. 保留所有权利.此源代码的使用受 MIT 风格的许可证管理,该许可证可以在 http://angular.io/license */的许可证文件中找到
有谁知道为什么它会像在线表格一样显示但缺少排序功能?
对于可能遇到此问题的其他任何人:问题是我没有在角度材料网站上正确阅读 API 参考,该部分说我必须导入 MatSortModule.在我将 app.module.ts 中的导入列表更改为
导入:[浏览器模块,垫表模块,垫排序模块],
效果很好
I am trying to get the mat-table
sorting to work locally, and while I can get the data to show up as expected, clicking on the header row does not do the sorting as it does on online examples (nothing happens at all).
I am trying to get this demo working locally:
https://material.angular.io/components/sort/overview
https://plnkr.co/edit/XF5VxOSEBxMTd9Yb3ZLA?p=preview
I have generated a new project with Angular CLI, then followed these steps: https://material.angular.io/guide/getting-started
Here are my local files:
app.module.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 { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
}
app.component.html
<div style="text-align:center">
<h1>
Welcome to {{title}}!
</h1>
<table-sorting-example></table-sorting-example>
</div>
table-sorting-example.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 -->
table-sorting-example.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 */
Does anyone have an idea of why it would show up like the online table but lack the sorting functionality?
For anyone else who may have this problem: The problem was I didn't read the API reference properly on the angular materials website, the part that said I had to import MatSortModule. After I changed my imports list in app.module.ts to
imports: [
BrowserModule,
MatTableModule,
MatSortModule
],
it worked fine
这篇关于垫表排序演示不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!