Sun*_*arg 26 datatable angular-material2 angular
我正在尝试实现Material2数据表.但我无法理解如何以正确的方式使用它.
import {Component, ElementRef, ViewChild} from '@angular/core';
import {DataSource} from '@angular/cdk';
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';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/observable/fromEvent';
@Component({
selector: 'table-filtering-example',
styleUrls: ['table-filtering-example.css'],
templateUrl: 'table-filtering-example.html',
})
export class TableFilteringExample {
displayedColumns = ['userId', 'userName', 'progress', 'color'];
exampleDatabase = new ExampleDatabase();
dataSource: ExampleDataSource | null;
@ViewChild('filter') filter: ElementRef;
ngOnInit() {
this.dataSource = new ExampleDataSource(this.exampleDatabase);
Observable.fromEvent(this.filter.nativeElement, 'keyup')
.debounceTime(150)
.distinctUntilChanged()
.subscribe(() => {
if (!this.dataSource) { return; }
this.dataSource.filter = this.filter.nativeElement.value;
});
}
}
/** 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> {
_filterChange = new BehaviorSubject('');
get filter(): string { return this._filterChange.value; }
set filter(filter: string) { this._filterChange.next(filter); }
constructor(private _exampleDatabase: ExampleDatabase) {
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._filterChange,
];
return Observable.merge(...displayDataChanges).map(() => {
return this._exampleDatabase.data.slice().filter((item: UserData) => {
let searchStr = (item.name + item.color).toLowerCase();
return searchStr.indexOf(this.filter.toLowerCase()) != -1;
});
});
}
disconnect() {}
}
Run Code Online (Sandbox Code Playgroud)
以上是数据表的代码,对我来说非常混乱.甚至他们的文档也很差.有人能解释一下上面代码的流程是什么吗?
如果您觉得问题太基本无法问,请忽略?
Ata*_*hez 23
您的示例中的代码是通用表的定义,使用material2规范中的新cdk组件.你必须记住md-table它的可视化实现cdk-table,因此你需要声明一个cdk,其模型与HTML中的md-model兼容.
例如:
我声明了cdk-table以下实现:
Material2中的新CDK组件,使用:
import { DataSource } from '@angular/cdk';
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';
Run Code Online (Sandbox Code Playgroud)
我定义了一个displayedColumns数组,这些项是我的HTML表中的列,按顺序:
displayedColumns = ['userId', 'userName', 'progress'];
Run Code Online (Sandbox Code Playgroud)
类型的数据库ExampleDatabase(特定于手动定义的对象):
exampleDatabase = new ExampleDatabase();
Run Code Online (Sandbox Code Playgroud)
最后,我宣布一个dataSource,这是我数据的来源.它是一个手动定义或数据为null的对象.
dataSource: ExampleDataSource | null;
Run Code Online (Sandbox Code Playgroud)
在ngOnInit()方法中,我只是声明我的参数为my dataSource的新ExampleDataSource参数exampleDataBase.
好,现在实现其余的代码:
首先,声明一个接口DataBase.这对于保持数据的一致性非常重要,数据库必须遵守已定义的方案.在此示例中,数据库有三列:id,name和progress:
export interface UserData {
id: number;
name: string;
progress: string;
}
Run Code Online (Sandbox Code Playgroud)
接下来的一点是创建一个类(Object)ExampleDatabase,其中包含我的数据定义DataBase.您可以创建用于连接到实际数据库(PostgreSQL,MongoDB)的服务,获取真实数据并在另一种方法中为cdk-datatable创建对象,但是在此示例中,我们使用在运行时模拟的内存数据库.
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() {
return {
id: 1,
name: 'example',
progress: Math.round(Math.random() * 100).toString()
};
}
}
Run Code Online (Sandbox Code Playgroud)
好的,最后我用my的定义创建了第二个类DataSource.
export class ExampleDataSource extends DataSource<any> {
constructor(private _exampleDatabase: ExampleDatabase) {
super();
}
/** Connect function called by the table to retrieve one stream containing the data to render. */
connect(): Observable<UserData[]> {
return this._exampleDatabase.dataChange;
}
disconnect() { }
}
Run Code Online (Sandbox Code Playgroud)
此方法确保数据格式正确,并释放与DataBase(在内存中)的"连接" 以获取其中的数据.
最后,使用HTML中的md-table组件或cdk-table组件.该md-table组件使用材料设计风格,并cdk-table使用通用样式..
MD-表:
<div class="example-container mat-elevation-z8">
<md-table #table [dataSource]="dataSource">
<!-- ID Column -->
<ng-container cdkColumnDef="userId">
<md-header-cell *cdkHeaderCellDef> ID </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.id}} </md-cell>
</ng-container>
<!-- Progress Column -->
<ng-container cdkColumnDef="progress">
<md-header-cell *cdkHeaderCellDef> Progress </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.progress}}% </md-cell>
</ng-container>
<!-- Name Column -->
<ng-container cdkColumnDef="userName">
<md-header-cell *cdkHeaderCellDef> Name </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.name}} </md-cell>
</ng-container>
<md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
<md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>
</md-table>
</div>
Run Code Online (Sandbox Code Playgroud)
CDK-表:
<div class="example-container mat-elevation-z8">
<cdk-table #table [dataSource]="dataSource" class="example-table">
<!-- ID Column -->
<ng-container cdkColumnDef="userId">
<cdk-header-cell *cdkHeaderCellDef class="example-header-cell"> ID </cdk-header-cell>
<cdk-cell *cdkCellDef="let row" class="example-cell"> {{row.id}} </cdk-cell>
</ng-container>
<!-- Progress Column -->
<ng-container cdkColumnDef="progress">
<cdk-header-cell *cdkHeaderCellDef class="example-header-cell"> Progress </cdk-header-cell>
<cdk-cell *cdkCellDef="let row" class="example-cell"> {{row.progress}}% </cdk-cell>
</ng-container>
<!-- Name Column -->
<ng-container cdkColumnDef="userName">
<cdk-header-cell *cdkHeaderCellDef class="example-header-cell"> Name </cdk-header-cell>
<cdk-cell *cdkCellDef="let row" class="example-cell"> {{row.name}} </cdk-cell>
</ng-container>
<cdk-header-row *cdkHeaderRowDef="displayedColumns" class="example-header-row"></cdk-header-row>
<cdk-row *cdkRowDef="let row; columns: displayedColumns;" class="example-row"></cdk-row>
</cdk-table>
</div>
Run Code Online (Sandbox Code Playgroud)
其余的实现,搜索,菜单,复选框等是您负责实现操作信息的逻辑.
有关更多详细信息,请使用有关cdk-table的文档:
https://material.angular.io/guide/cdk-table
结果:
做我的佩剑和成就,我理解我的解释,并为我的英语道歉.我在学习.
这是为查看出勤创建的自定义代码,现在我已对数据进行了硬编码,您可以调用服务而不是获取动态数据.
app.component.ts
import { Component, OnInit, ElementRef, ViewEncapsulation, ViewChild } from '@angular/core';
import { DataSource } from '@angular/cdk';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
import { MdPaginator, MdSort } from '@angular/material';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/observable/merge';
import 'rxjs/add/operator/map';
declare let d3: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
displayedColumns = ['shiftDate', 'swipeIn', 'swipeOut', 'duration', 'status'];
exampleDatabase = new ExampleDatabase();
dataSource: ExampleDataSource | null;
@ViewChild(MdPaginator) paginator: MdPaginator;
@ViewChild(MdSort) sort: MdSort;
ngOnInit() {
this.dataSource = new ExampleDataSource(this.exampleDatabase, this.paginator, this.sort);
}
}
export interface attendanceData {
shiftDate: string;
swipeIn: string;
swipeOut: string;
duration: string;
status: 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<attendanceData[]> = new BehaviorSubject<attendanceData[]>([]);
get data(): attendanceData[] {
let data = [
{
"shiftDate": "17-July-2017",
"swipeIn": "10:00 AM",
"swipeOut": "06:00 PM",
"duration": "8 Hours",
"status": "PRESENT"
},
{
"shiftDate": "16-July-2017",
"swipeIn": "9:00 AM",
"swipeOut": "5:00 AM",
"duration": "7 Hours",
"status": "PRESENT"
}
];
return data;
}
constructor() {
this.dataChange.next(this.data);
}
}
export class ExampleDataSource extends DataSource<any> {
_filterChange = new BehaviorSubject('');
get filter(): string { return this._filterChange.value; }
set filter(filter: string) { this._filterChange.next(filter); }
constructor(private _exampleDatabase: ExampleDatabase, private _paginator: MdPaginator, private _sort: MdSort) {
super();
}
/** Connect function called by the table to retrieve one stream containing the data to render. */
connect(): Observable<attendanceData[]> {
const displayDataChanges = [
this._exampleDatabase.dataChange,
this._paginator.page,
this._sort.mdSortChange
];
return Observable.merge(...displayDataChanges).map(() => {
// const data = this._exampleDatabase.data.slice();
const data = this.getSortedData();
// Grab the page's slice of data.
const startIndex = this._paginator.pageIndex * this._paginator.pageSize;
return data.splice(startIndex, this._paginator.pageSize);
});
}
disconnect() { }
getSortedData(): attendanceData[] {
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 'shiftDate': [propertyA, propertyB] = [a.shiftDate, b.shiftDate]; break;
case 'swipeIn': [propertyA, propertyB] = [a.swipeIn, b.swipeIn]; break;
case 'swipeOut': [propertyA, propertyB] = [a.swipeOut, b.swipeOut]; break;
case 'duration': [propertyA, propertyB] = [a.duration, b.duration]; break;
}
let valueA = isNaN(+propertyA) ? propertyA : +propertyA;
let valueB = isNaN(+propertyB) ? propertyB : +propertyB;
return (valueA < valueB ? -1 : 1) * (this._sort.direction == 'asc' ? 1 : -1);
});
}
}
Run Code Online (Sandbox Code Playgroud)
app.component.html
<div class="example-container mat-elevation-z8">
<md-table #table [dataSource]="dataSource" mdSort>
<!--- 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 cdkColumnDef="shiftDate">
<md-header-cell *cdkHeaderCellDef md-sort-header> Shift Date </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.shiftDate}} </md-cell>
</ng-container>
<!-- Progress Column -->
<ng-container cdkColumnDef="swipeIn">
<md-header-cell *cdkHeaderCellDef md-sort-header> Swipe In </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.swipeIn}}% </md-cell>
</ng-container>
<!-- Name Column -->
<ng-container cdkColumnDef="swipeOut">
<md-header-cell *cdkHeaderCellDef> Swipe Out </md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.swipeOut}} </md-cell>
</ng-container>
<!-- Color Column -->
<ng-container cdkColumnDef="duration">
<md-header-cell *cdkHeaderCellDef>Duration</md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.duration}} </md-cell>
</ng-container>
<!-- Color Column -->
<ng-container cdkColumnDef="status">
<md-header-cell *cdkHeaderCellDef>Status</md-header-cell>
<md-cell *cdkCellDef="let row"> {{row.status}} </md-cell>
</ng-container>
<md-header-row *cdkHeaderRowDef="displayedColumns"></md-header-row>
<md-row *cdkRowDef="let row; columns: displayedColumns;"></md-row>
</md-table>
<md-paginator #paginator
[length]="exampleDatabase.data.length"
[pageIndex]="0"
[pageSize]="25"
[pageSizeOptions]="[5, 10, 25, 100]">
</md-paginator>
</div>
Run Code Online (Sandbox Code Playgroud)
app.module.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { MaterialModule, MdTableModule } from '@angular/material';
import { FlexLayoutModule } from '@angular/flex-layout';
import { CdkTableModule } from '@angular/cdk';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserAnimationsModule,
CdkTableModule,
BrowserModule,
MaterialModule, MdTableModule,
FlexLayoutModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32823 次 |
| 最近记录: |