【问题标题】:Mat data-table paginate and sort not workingMat数据表分页和排序不起作用
【发布时间】:2019-08-21 02:12:17
【问题描述】:

我的 HTML 代码是这样的:

<div class="mat-elevation-z8" *ngIf="Model">
  <br>
  <mat-form-field class="col-md-3 col-lg-3">
    <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
  </mat-form-field>


  <table mat-table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="StartTime">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> StartTime </th>
      <td mat-cell *matCellDef="let row" style="width: 15%"> {{row.call_start_time | date:'dd-MM-yyyy HH:mm:ss'}} </td>
    </ng-container>

    <ng-container matColumnDef="Duration">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Duration </th>
      <td mat-cell *matCellDef="let row"> {{row.call_total_duration}} </td>
    </ng-container>


    <ng-container matColumnDef="CallType">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> CallType </th>
      <td mat-cell *matCellDef="let row" style="width: 5%"> {{row.call_type}} </td>
    </ng-container>

    <ng-container matColumnDef="CLI">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> CLI </th>
      <td mat-cell *matCellDef="let row" style="width: 15%"> {{row.call_cli}} </td>
    </ng-container>

    <ng-container matColumnDef="Campaign">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Campaign </th>
      <td mat-cell *matCellDef="let row" style="width: 20%"> {{row.call_service_name}} </td>
    </ng-container>
    &nbsp;&nbsp;

    <ng-container matColumnDef="Agent">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Agent </th>
      <td mat-cell *matCellDef="let row"> {{row.call_agent_id}} </td>
    </ng-container>

    <ng-container matColumnDef="Disposition">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Disposition </th>
      <td mat-cell *matCellDef="let row" style="width: 20%"> {{row.call_end_type_name}} </td>
    </ng-container>

    <ng-container matColumnDef="Remarks">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Remarks </th>
      <td mat-cell *matCellDef="let row" style="width: 20%"> {{row.call_remark}} </td>
    </ng-container>

    <ng-container matColumnDef="TransfferedTo">
      <th mat-header-cell *matHeaderCellDef mat-sort-header style="width: 5%"> TransfferedTo </th>
      <td mat-cell *matCellDef="let row" style="width: 5%"> {{row.call_child_callnumber}} </td>
    </ng-container>

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

  <mat-paginator [pageSizeOptions]="[5,10, 25]"></mat-paginator>
</div>

我提出的问题: mat-sort not working on mat-table

我提到了一些问题,但他们都在调用 ngOnInit() 上的服务,但我需要在我的 .ts 文件中的 ngSubmit() 方法上调用服务。

分页和排序不起作用。我认为我的类型脚本文件有问题,它看起来像这样:

import { Component, OnInit, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { startWith, map } from 'rxjs/operators';
import { CampaignService } from 'services/campaign.service';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';



export interface State {
  Name: string;
  Id: number;
}
@Component({
  selector: 'app-logs',
  templateUrl: './logs.component.html',
  styleUrls: ['./logs.component.css']
})
export class LogsComponent implements OnInit {
  dataSource: MatTableDataSource<any>;
  displayedColumns: string[] = ['StartTime', 'Duration', 'CallType', 'CLI', 'Campaign' , 'Agent' , 'Disposition' , 'Remarks' , 'TransfferedTo'];

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(private webService: CampaignService) {
  
  }


  FromDate: any;
  ToDate: any;
  Campaign: any;
  Agent: any;
  MobileNumber: any;
  stateCtrl = new FormControl();
  filteredStates: Observable<State[]>;
  Model: any;
  Data: any;
  Result: any;

  private _filterStates(value: string): State[] {
    const filterValue = value.toLowerCase();

    return this.Data.filter(state => state.Name.toLowerCase().indexOf(filterValue) === 0);
  }

  ngOnInit() {

    //this.dataSource = new MatTableDataSource(this.Result);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }



  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  onSubmit(data) {

    const deatails = JSON.stringify({
      FromDate: FromDate,
      ToDate: ToDate,
      Campaign: this.Campaign,
      Agent: data.Agent,
      MobileNumber: data.MobileNumber
    });


    this.webService.CallDetails(deatails)
      .subscribe(
        response => {
          this.Model = response;
          this.Result = this.Model.log
          this.dataSource = new MatTableDataSource( this.Result);
    
        },
        (error) => console.error(error)
      );
   
  }


}

谁能指出我哪里出错了?非常感谢。

【问题讨论】:

标签: html angular-material angular6


【解决方案1】:

确保你添加了

import { MatPaginatorModule, MatSortModule } from '@angular/material';

@NgModule({ exports: [ MatPaginatorModule, MatSortModule] })

在相应的模块中

【讨论】:

  • 对应的模块是什么意思?并且它已经导入到我的 app.module.ts 文件中。
  • 你有什么理由要创建新的 MatTableDataSource this.dataSource = new MatTableDataSource( this.Result); 吗?尝试改用this.dataSource=this.Result。我假设您指向分页器和排序的数据源与您在this.dataSource = new MatTableDataSource( this.Result); 中设置的数据源不同
  • 最初我尝试使用您指出的语法,但它不起作用。所以我使用了 angular-material 给出的语法。但它仍然没有回答这个问题。
  • 回复是否填充到this.Result = this.Model.log 中?
  • 是的。我能够获取数据并且能够成功地将数据绑定到网格。唯一的问题是分页和排序
【解决方案2】:

在 ngOnInit 方法中,您似乎正在使用尚未初始化的 dataSource 成员。

您可以摆脱方法 ngOnInit 并将其内容移至处理 web 服务结果的位置。

this.webService.CallDetails(deatails)
  .subscribe(
     response => {
        this.Model = response;
        this.Result = this.Model.log
        this.dataSource = new MatTableDataSource( this.Result);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;        
     },
     error => console.error(error)
  ); 

【讨论】:

    【解决方案3】:

    这就是我解决问题的方法,以防万一有人需要它:

     @ViewChild(MatSort) sort: MatSort;
     
     @ViewChild(MatPaginator) set matPaginator(mp: MatPaginator) {
        this.paginator = mp;
        this.setDataSourceAttributes();
        }
        
     dataSource = new MatTableDataSource();  
     displayedColumns: string[] = ['call_start_time', 'call_agent_login_id', 'call_cli', 'call_service_name', 'call_type', 'Play'];
     
     setDataSourceAttributes() {
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      }
      
      onSubmit() {
    
        this.webService.CallDetails(deatails)
          .subscribe(
            response => {
            
              this.Model = response;
              this.Result = this.Model.log;
              this.dataSource = new MatTableDataSource(this.Result);
            },
            
            (error) => console.error(error)
          );
    
      }
    <table mat-table [dataSource]="dataSource" matSort>
    
      <ng-container matColumnDef="call_start_time" class="text-center">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> StartTime </th>
        <td mat-cell *matCellDef="let row" style="width: 25%"> {{row.call_start_time | date:'dd-MM-yyyy HH:mm:ss'}}
        </td>
      </ng-container>
    
      <ng-container matColumnDef="call_agent_login_id">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Agent </th>
        <td mat-cell *matCellDef="let row"> {{row.call_agent_login_id}} </td>
      </ng-container>
    
      <ng-container matColumnDef="call_cli">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> CLI </th>
        <td mat-cell *matCellDef="let row" style="width: 15%"> {{row.call_cli}} </td>
      </ng-container>
    
      <ng-container matColumnDef="call_service_name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Campaign </th>
        <td mat-cell *matCellDef="let row" style="width:20px;"> {{row.call_service_name}} </td>
      </ng-container>
      
      <ng-container matColumnDef="call_type">
        <th mat-header-cell *matHeaderCellDef mat-sort-header style="max-width:20px !important"> CallType </th>
        <td mat-cell *matCellDef="let row"> {{row.call_type}} </td>
      </ng-container>
      <ng-container matColumnDef="Play">
        <th mat-header-cell *matHeaderCellDef> Play</th>
        <td mat-cell *matCellDef="let row">
    
          <button *ngIf="row.filepath" (click)="openDialog(row.filepath)" mat-stroked-button style="min-width:1%;" color="primary"><img src="../../assets/Images/play.png" /> </button>
    
          <button *ngIf="!row.filepath" mat-raised-button disabled style="min-width:1%;" color="primary"><img src="../../assets/Images/unavailable.png" /></button>
        </td>
    
      </ng-container>
    
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;">
      </tr>
    </table>
    
    <mat-paginator [pageSizeOptions]="[5,10, 25]"></mat-paginator>

    我确保 ma​​tColumDef 和绑定名称相同,以便排序正常工作。

    【讨论】:

      【解决方案4】:

      不幸的是,这是一个 Angular 问题,其中 ViewChild 无法在 ngAfterViewInit 中使用 *ngIf 捕获元素。

      https://github.com/angular/components/issues/8705#issuecomment-377266657

      【讨论】:

        【解决方案5】:

        参考angular Material Documentation on Tables here:

        ngAfterViewInit() {
            this.dataSource.paginator = this.paginator;
            this.dataSource.sort = this.sort;
          }
        

        注意 - this.paginator 和 this.sort 被称为 - AfterViewInit 如果您在 onInit 下调用它们 - 这将不起作用。

        因此,改为 - 调用如下:

        export class CategoriesListComponent implements OnInit, AfterViewInit {
        
          // VARIABLES
          dataSource = new MatTableDataSource<Category>([]);
          displayedColumns: string[] = ['id', 'name', 'icon', 'color', 'image'];
        
          @ViewChild(MatPaginator) paginator!: MatPaginator;
          @ViewChild(MatSort) sort!: MatSort;
        
          constructor(
            private categoriesService: CategoriesService
          ) { }
        
          ngOnInit(): void {
            this._getDataTableCategoriesData();
          }
        
          ngAfterViewInit(): void {
              this._setTableAttributes();
          }
        
          private _getDataTableCategoriesData() {
            this.categoriesService.getCategories().subscribe(
              (categories) => {
                this.dataSource.data = categories;
              });
          }
        
          private _setTableAttributes() {
            this.dataSource.paginator = this.paginator;
            this.dataSource.sort = this.sort;
          }
        
          applyFilter(event: Event) {
            const filterValue = (event.target as HTMLInputElement).value;
            this.dataSource.filter = filterValue.trim().toLowerCase();
        
            if (this.dataSource.paginator) {
              this.dataSource.paginator.firstPage();
            }
          }
        

        【讨论】:

          猜你喜欢
          • 2020-01-20
          • 2018-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-07
          • 1970-01-01
          相关资源
          最近更新 更多