【问题标题】:Angular Material Data Table not sorting?角度材料数据表未排序?
【发布时间】:2019-12-27 03:50:19
【问题描述】:

[STACKBLITS LINK] I'm attempting a minimal angular material data table with sorting.

我已经添加了 MatSortModule,在类中实现了 @ViewChild,添加了指令,设置了 dataSource.sort 属性等,当我将鼠标悬停时,我在桌子上看到了箭头,但数据没有排序。

想法?

    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>

【问题讨论】:

    标签: javascript angular typescript angular-material


    【解决方案1】:

    MatSortViewChildundefined ngOnInit,因为视图尚未初始化。要解决此问题,请在使用 ngAfterViewInit 生命周期挂钩初始化视图后,在 dataSource 上设置 MatSort

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

    【讨论】:

      【解决方案2】:

      我有同样的问题,你需要设置 MatSort。 这就是我修复它的方法

      @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;
      }
      

      我希望它有所帮助。 :)

      【讨论】:

      • 我们必须等到AfterViewInit 才能确保sortDirective 已完全初始化。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 2019-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多