簡體   English   中英

角度材料數據表沒有排序?

[英]Angular Material Data Table not sorting?

[STACKBLITS LINK]我正在嘗試一個帶有排序的最小角度材料數據表

我添加了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>

ViewChildMatSortundefinedngOnInit自認為尚未初始化。 要解決此問題,請在使用ngAfterViewInit生命周期掛鈎初始化視圖后在dataSource上設置MatSort

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

我有同樣的問題,你需要設置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;
}

我希望它有所幫助。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM