简体   繁体   English

角度材料数据表没有排序?

[英]Angular Material Data Table not sorting?

[STACKBLITS LINK] I'm attempting a minimal angular material data table with sorting . [STACKBLITS LINK]我正在尝试一个带有排序的最小角度材料数据表

I've added the MatSortModule, implemented @ViewChild in the class, added the directives, set the dataSource.sort property etc. and I get the arrow on the table when I mouse hover, but the data does not sort. 我添加了MatSortModule,在类中实现了@ViewChild ,添加了指令,设置了dataSource.sort属性等,当鼠标悬停时我得到了表上的箭头,但是数据没有排序。

Thoughts? 思考?

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { MatTableDataSource, MatSort } from "@angular/material";

    class Todo {
      id: string;
      description: string;
      complete: boolean;
    }
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      @ViewChild(MatSort, {static: false}) sort: MatSort;

      /**
      * Control column ordering and which columns are displayed.
      */
      displayedColumns:string[] =  ['id'];
      dataSource: MatTableDataSource<Todo>;

      ngOnInit() {
        const todos: Todo[] = [
          { id: '123', description: 'Complete me!', complete: false },
          { id: '321', description: 'You Completed me!', complete: true }];
        this.dataSource = new MatTableDataSource(todos);
        this.dataSource.sort = this.sort;
      }
    }


    <mat-table class="mat-elevation-z8" [dataSource]="dataSource" matSort>
      <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
        <mat-cell *matCellDef="let row;">{{row.id}}</mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="displayedColumns">
      </mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
    </mat-table>

The ViewChild for MatSort is undefined at ngOnInit since the view has not yet been initialized. ViewChildMatSortundefinedngOnInit自认为尚未初始化。 To resolve this, set the MatSort on your dataSource after the view has initialized by using the ngAfterViewInit lifecycle hook. 要解决此问题,请在使用ngAfterViewInit生命周期挂钩初始化视图后在dataSource上设置MatSort

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

I had the same issue, you need to set the MatSort. 我有同样的问题,你需要设置MatSort。 This is how I fixed it 这是我修复它的方式

@ViewChild(MatSort, {static: false}) set  sortMeeting (ms: MatSort){
this._sort = ms;
this.renewDataSource(); }

............................................ ............................................

ngOnInit(){
this.dataSource = new MatTableDataSource(todos);
this.renewDataSource();
}


renewDataSource() {
this.dataSource.sort = this._sort;
}

I hope it helps. 我希望它有所帮助。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM