【发布时间】:2021-04-06 20:03:18
【问题描述】:
我使用ng generate @angular/material:material-table --name <component-name> 命令创建了我的角度数据表。我遵循了一些关于如何使用 http 请求填充此数据表的教程。我也尝试对数据表应用一些过滤。
这是我的 op-dta-datasource.ts 文件代码。
export interface OpDataSecondItem {
id: number;
title:string;
close_date:Date;
}
export class OpDataSecondDataSource extends DataSource<OpDataSecondItem> {
data: OpDataSecondItem[];
paginator: MatPaginator;
sort: MatSort;
constructor() {
super();
}
connect(): Observable<OpDataSecondItem[]> {
// Combine everything that affects the rendered data into one update
// stream for the data-table to consume.
const dataMutations = [
observableOf(this.data),
this.paginator.page,
this.sort.sortChange
];
return merge(...dataMutations).pipe(map(() => {
return this.getPagedData(this.getSortedData([...this.data]));
}));
}
......
这是我的 op-dta.component.ts
@Component({
selector: 'op-data-second',
templateUrl: './op-data-second.component.html',
styleUrls: ['./op-data-second.component.css']
})
export class OpDataSecondComponent implements AfterViewInit, OnInit {
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatTable) table: MatTable<OpDataSecondItem>;
dataSource: OpDataSecondDataSource;
searchKey: string;
displayedColumns = ['id', 'title','close_date','published_date'];
constructor(private service: HttpserviceService){}
ngOnInit() {
this.dataSource = new OpDataSecondDataSource();
this.service.getOps('').subscribe((data:OpDataSecondItem[])=>{
this.dataSource.data = data;
});
}
ngAfterViewInit() {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
this.table.dataSource = this.dataSource;
}
onSearchClear() {
this.searchKey = "";
this.applyFilter();
}
applyFilter() {
this.dataSource.data['title'].filter = this.searchKey.trim().toLowerCase();
}
}
还有我的 html 代码。
<div class="search-div">
<mat-form-field class="search-form-field" >
<input matInput [(ngModel)]="searchKey" placeholder="Search" autocomplete="off" (keyup)="applyFilter()">
<button mat-button matSuffix mat-icon-button aria-label="Clear"*ngIf="searchKey" (click)="onSearchClear()">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>
</div>
<div class="mat-elevation-z8">
<table mat-table class="full-width-table" matSort aria-label="Elements">
<!-- Id Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header><strong>Id</strong> </th>
<td mat-cell *matCellDef="let row"> <span>{{row.id}}</span></td>
</ng-container>
.............
<mat-paginator #paginator
[length]="dataSource?.data.length"
[pageIndex]="0"
[pageSize]="10"
[pageSizeOptions]="[5, 10, 25, 50]"
showFirstLastButtons>
</mat-paginator>
</div>
我编写的过滤器方法不起作用,我看到一些代码他们正在使用我不理解的 mattabledatasource 并且我无法将我的代码转换为那种方式。任何人都可以帮助我如何编写有效的过滤方法,以及如何转换我的代码以便以我当前模块不会中断的方式使用 MatTableDataSource。
【问题讨论】: