Сортировка не работает угловой дизайн таблицы материалов - PullRequest
0 голосов
/ 27 апреля 2018

Используя таблицу Angular Material Design, я просто пытаюсь отсортировать заголовки двух столбцов в таблице данных. (Это столбцы Имя сотрудника и Название должности в приведенном ниже коде.) Оба не сортируют. Не уверен почему. Вот мой код и спасибо, CM

работник-table.component.html

<div>

  <mat-table [dataSource] = "dataSource" matSort>
    <ng-container matColumnDef="photo">
      <mat-header-cell *matHeaderCellDef>Profile</mat-header-cell>
      <mat-cell *matCellDef="let employee"><img width = "100" height = "100" src = "../assets/images/{{employee.username}}.jpg" >
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef mat-sort-header>Employee Name</mat-header-cell>
      <mat-cell *matCellDef="let employee">{{employee.name}}</mat-cell>
    </ng-container>


    <ng-container matColumnDef="position">
      <mat-header-cell *matHeaderCellDef mat-sort-header>Job Title</mat-header-cell>
      <mat-cell *matCellDef="let employee">{{employee.position}}</mat-cell>
    </ng-container>

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

  </mat-table>
</div>

работник-table.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {MatSort, MatSortable, MatTableDataSource} from '@angular/material';
import {EmployeeService} from '../employee.service';

@Component({
  selector: 'app-employee-table',
  templateUrl: './employee-table.component.html',
  styleUrls: ['./employee-table.component.css']
})
export class EmployeeTableComponent implements OnInit {
  @ViewChild(MatSort) sort: MatSort;
  dataSource;
  displayedColumns = ['photo', 'name', 'position'];

  constructor() { }
  ngOnInit() {   
    this.dataSource =[
            {
              "id": 1,
              "name": "Leanne Grahamz",
              "username": "Bret",
              "position": "Software Developer"
            },
            {
              "id": 2,
              "name": "Ervin Howell",
              "username": "Antonette",
              "position": "Graphic Designer"
            },
            {
              "id": 3,
              "name": "Clementine Bauch",
              "username": "Samantha",
              "position": "Front End Developer"
            },
            {
              "id": 4,
              "name": "Patricia Lebsack",
              "username": "Karianne",
              "position": "Full Stack Developer"
            },
            {
              "id": 5,
              "name": "Chelsey Dietrich",
              "username": "Kamren",
              "position": "Database Administrator" 
            }
    ]; //End data object

    this.dataSource.sort = this.sort;

  }//End ng onInit

}//End class EmployeeTableComponent

Ответы [ 2 ]

0 голосов
/ 10 сентября 2018

В качестве альтернативы, вы также можете использовать тайм-аут для сортировки (и нумерацию страниц, если необходимо), например:

setTimeout(() => {
  this.tableDataSource.sort = this.sort;
  this.tableDataSource.paginator = this.paginator;
});
0 голосов
/ 27 апреля 2018

Вы устанавливаете сортировку источника данных this.dataSource.sort = this.sort; слишком рано в жизненном цикле. Как следует из примеров material.angular.io , вы должны установить сортировку источника данных после представления init:

Скопировано из примера material.angular.io :

 /**
   * Set the sort after the view init since this component will
   * be able to query its view for the initialized sort.
   */
  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }

Вам также следует отредактировать инициализацию источника данных:

ngOnInit() {
 this.dataSource = new MatTableDataSource([{
     "id": 1,
     "name": "Leanne Grahamz",
     "username": "Bret",
     "position": "Software Developer"
    }, 
    ...
    {
     "id": 5,
     "name": "Chelsey Dietrich",
     "username": "Kamren",
     "position": "Database Administrator"
    }
   ]);
}

Вот правка исходного примера с вашим кодом.

...