物料表未排序记录

时间:2019-05-26 22:07:46

标签: angular

我找不到我的脚本出了什么问题,列表加载确定,但是单击表头时排序不起作用。

我尝试将排序部分放在响应的TimeOut内,然后将其移至ngAfterViewInit()函数。除此以外,我的应用程序上的其他所有内容都正常运行。

以下是ts代码:

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CatalogosService } from 'src/app/services/catalogos.service';
import { MatPaginator, MatSort, MatTableDataSource, MatTableModule, MatTable, 
  MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Response } from 'src/app/classes/response';

@Component({
  selector: 'app-lista-proveedores',
  templateUrl: './lista-proveedores.component.html',
  styleUrls: ['./lista-proveedores.component.css']
})
export class ListaProveedoresComponent implements OnInit {

  proveedores: any[];
  listData: MatTableDataSource<any>;
  displayColumns: string[]=['id','nombre','acciones'];
  searchKey: string;
  //spinner: SpinnerComponent= new SpinnerComponent;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator; 

  constructor(private proveedorService: CatalogosService,
              private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.getRecords();
  }

  getRecords(): void{
    this.proveedorService.getItems()
    .subscribe(
      (response: Response) => {
        //this.proveedores = response.object;
        this.listData= new MatTableDataSource(response.object);
        this.listData.sort= this.sort;
        this.listData.paginator= this.paginator;
        console.log("List data: ", this.sort);
      });
      this.changeDetectorRefs.detectChanges();
  }

}

这是html:

<div class="col-lg-12">
  <div class="row">
      <div class="col-lg-9 text-center">
          <h3 class="title-divider">
              <span>List</span>
          </h3>
      </div>
      <div class="col-lg-3 text-center">
          &nbsp;
      </div>
  </div>
  <div class="row">
      <div class="col-lg-12">
          <div class="mat-elevation-z8">
              <mat-table #table [dataSource]="listData" matSort>
                  <ng-container matColumnDef="id">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.ID}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="nombre">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>Nombre</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{element.Name}}</mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="acciones">
                      <mat-header-cell *matHeaderCellDef>Acciones</mat-header-cell>
                      <mat-cell *matCellDef="let row">
                          <button mat-icon-button (click)="onDetail(row)"><mat-icon>details</mat-icon></button>
                          <button mat-icon-button (click)="onEdit(row)"><mat-icon>launch</mat-icon></button>
                          <button mat-icon-button color="warn" (click)="onDelete(row)"><mat-icon>delete_outline</mat-icon></button>
                      </mat-cell>
                  </ng-container>
                  <ng-container matColumnDef="loading">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          Loading data
                      </mat-footer-cell>
                  </ng-container>
                  <ng-container matColumnDef="noData">
                      <mat-footer-cell *matFooterCellDef colspan="6">
                          No data
                      </mat-footer-cell>
                  </ng-container>
                  <mat-header-row *matHeaderRowDef="displayColumns; sticky:true "></mat-header-row>
                  <mat-row *matRowDef="let row; columns: displayColumns"></mat-row>
                  <mat-footer-row *matFooterRowDef="['loading']" [ngClass]="{'hide':listData!=null}"></mat-footer-row>
                  <mat-footer-row *matFooterRowDef="['noData']" [ngClass]="{'hide':!(listData!=null && listData.data.length==0)}"></mat-footer-row>
              </mat-table>
              <mat-paginator [pageSizeOptions]="[5, 10, 15, 25]" [pageSize]="5" showFirstLastButtons></mat-paginator>
          </div>
      </div>
  </div>

</div>

这也是显示MatSort对象的控制台日志:

MatSort {_disabled: false, _isInitialized: true, _pendingSubscribers: null, initialized: Observable, sortables: Map(2), …}
direction: (...)
disableClear: (...)
disabled: (...)
initialized: Observable
_isScalar: false
_subscribe: ƒ (subscriber)
arguments: (...)
caller: (...)
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: core.es5.js:474
[[Scopes]]: Scopes[4]
__proto__: Object
sortChange: EventEmitter
closed: false
hasError: false
isStopped: false
observers: (3) [Subscriber, Subscriber, Subscriber]
thrownError: null
__isAsync: false
_isScalar: false
__proto__: Subject
sortables: Map(2)
size: (...)
__proto__: Map
[[Entries]]: Array(2)
0: {"id" => MatSortHeader}
1: {"nombre" => MatSortHeader}
length: 2
start: "asc"
_direction: ""
_disabled: false
_isInitialized: true
_pendingSubscribers: null
_stateChanges: Subject {_isScalar: false, observers: Array(2), closed: false, isStopped: false, hasError: false, …}
__proto__: class_1

我已经在AppModule上导入了MatSortModule和MatTableModule,并且JS控制台没有显示任何错误。

3 个答案:

答案 0 :(得分:1)

进行了一些更改,使其更像我的操作方式,您可以将其复制进去看看是否可行吗?:

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { CatalogosService } from 'src/app/services/catalogos.service';
import { MatPaginator, MatSort, MatTableDataSource, MatTableModule, MatTable,
  MatDialog, MatDialogConfig, MatDialogRef, MAT_DIALOG_DATA } from 
'@angular/material';
import { Response } from 'src/app/classes/response';

@Component({
  selector: 'app-lista-proveedores',
  templateUrl: './lista-proveedores.component.html',
  styleUrls: ['./lista-proveedores.component.css']
})
export class ListaProveedoresComponent implements OnInit {

  proveedores: any[];
  public listData = new MatTableDataSource<any>();

  displayColumns: string[] = ['id', 'nombre', 'acciones'];
  searchKey: string;
  //spinner: SpinnerComponent= new SpinnerComponent;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(private proveedorService: CatalogosService,
              private dialog: MatDialog,
              private changeDetectorRefs: ChangeDetectorRef) { }

  ngOnInit() {
    this.getRecords();
  }

  getRecords(): void{
    this.proveedorService.getItems()
    .subscribe(
      (response: Response) => {
        //this.proveedores = response.object;
        this.listData.data = response;
        this.listData.sort = this.sort;
        this.listData.paginator= this.paginator;
        console.log("List data: ", this.sort);
      });
      this.changeDetectorRefs.detectChanges();
  }

}

还要检查您的大写对html中的matColumnDef是否正确。我认为情况可能与对象的实际情况不符。您以element.ID和matColumndef = id为例。 我刚刚进行了编辑,然后看到杰西在下面说了同样的话。所以先尝试一下。

答案 1 :(得分:1)

我的理解是,您定义的排序标题必须匹配确切的属性名称以进行排序。现在您有idID。因此,只需将其更改为:

displayColumns: string[]=['ID','nombre','acciones'];

<ng-container matColumnDef="ID">

答案 2 :(得分:0)

正如两条注释所述,问题在于列名(matColumnDef)与服务器中的模型不匹配。