首页 > 解决方案 > 如何使用数据表在angular7中设置搜索框、排序和分页

问题描述

您好,我正在尝试在 angular7 中获取分页和搜索过滤器,但我没有获得分页和搜索过滤器正在获取排序功能。还帮助我获取搜索过滤器代码。你能帮我解决这个问题吗

这里是 testm.component.html

   <mat-table #table [dataSource]="dataSource" matSort>
            <ng-container matColumnDef="{{column.id}}" *ngFor="let column of columnNames">
              <mat-header-cell *matHeaderCellDef mat-sort-header> {{column.value}} </mat-header-cell>
              <mat-cell *matCellDef="let element"> {{element[column.id]}} </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;">  </mat-row>
           </mat-table>
        <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>

和 testm.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import {MatPaginator, MatTableDataSource} from '@angular/material';
import { MatTableDataSource, MatSort } from '@angular/material';
    import { DataSource } from '@angular/cdk/table';

@Component({
  selector: 'app-testm',
  templateUrl: './testm.component.html',
  styleUrls: ['./testm.component.scss']
})
export class TestmComponent implements OnInit {

  constructor() { }
  dataSource;
  displayedColumns = [];
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;


  /**
   * Pre-defined columns list for user table
   */
  columnNames = [{
    id: "position",
    value: "No."

  }, {
    id: "name",
    value: "Name"
  },
  {
    id: "weight",
    value: "Weight"
  },
  {
    id: "symbol",
    value: "Symbol"
  }];

  ngOnInit() {
    this.displayedColumns = this.columnNames.map(x => x.id);
        this.createTable();
    this.dataSource.paginator = this.paginator;
  }
  createTable() {
    let tableArr: Element[] = [
    { position: 1, name: 'Hydrogen', weight: 12, symbol: 'H' },
    { position: 2, name: 'Helium', weight: 32, symbol: 'He' },
    { position: 3, name: 'Lithium', weight: 35, symbol: 'Li' },
    { position: 4, name: 'Beryllium', weight: 65, symbol: 'Be' },
    { position: 5, name: 'Boron', weight: 98, symbol: 'B' },
    { position: 6, name: 'Carbon', weight: 49, symbol: 'C' }
    ];
    this.dataSource = new MatTableDataSource(tableArr);
    this.dataSource.sort = this.sort;
  }

}
export interface Element {
  position: number,
  name: string,
  weight: number,
  symbol: string
}

标签: angulardatatableangular7

解决方案


对于排序和分页,您必须从@angular/core 导入“AfterViewInit”接口。

然后您将能够调用 ngAfterViewInit() 方法。例如,

ngAfterViewInit() {

this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;}

对于过滤,请在 Mat Table 顶部使用以下代码。例如,

<mat-form-field>
    <input matInput type="text" (keyup)="doFilter($event.target.value)" placeholder="Filter">
  </mat-form-field>

并在组件内部实现 doFilter()。

doFilter(filterValue: string) {
    console.log(filterValue);
    this.dataSource.filter = filterValue.trim().toLocaleLowerCase();
  }


推荐阅读