mat-sort и mat-paginator не работают на Angular Материал mat-table - PullRequest
0 голосов
/ 06 марта 2020

Я пытался использовать mat-sort и mat-paginator на моей таблице материалов, которая, похоже, не работает. Таблица получает данные в dataSource.data, и они также отображаются в mat-таблице, но свойства dataSource.sort и dataSource.paginator остаются undefined . Я попытался присвоить значения обоим свойствам как в ngOnInit (), так и в ngAfterViewInit (), как было предложено в других подобных вопросах, таких как приведенный здесь: сортировка по мату не работает на таблице матов , но ничего похоже на работу. Ниже приведен код для того же. Версия Angular Material - 8.2.3, а версия Angular - 8.3.25. Я буду рад любой помощи. Заранее спасибо:)

employee-list.component.ts

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { RestApiService } from '../shared/rest-api.service';
import { MatTableDataSource, MatSort, MatPaginator } from '@angular/material'; // Service used for Snackbar, Dialog,


@Component({
  selector: 'app-employees-list',
  templateUrl: './employees-list.component.html',
  styleUrls: ['./employees-list.component.scss']
})
export class EmployeesListComponent implements OnInit, AfterViewInit {

  public Employee: any = [];
  public dataSource: any;
  @ViewChild(MatSort, { static: true }) sort: MatSort;
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

  displayedColumns: string[] = ['id', 'name', 'email', 'phone', 'actions'];

  constructor(public restApi: RestApiService) { }

  ngOnInit() {
    this.loadEmployees();
  }

  // Get employees list
  loadEmployees() {
    return this.restApi.getEmployees().subscribe((data: {}) => {
      console.log(data);
      this.Employee = data;
      this.dataSource = new MatTableDataSource(this.Employee);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
      console.log(this.dataSource);
    });
  }

  ngAfterViewInit() {
  }

  // Delete employee
  deleteEmployee(id) {
    if (window.confirm('Are you sure, you want to delete?')) {
      this.restApi.deleteEmployee(id).subscribe(data => {
        this.loadEmployees();
      });
    }
  }

}

employee-list.component. html

<div *ngIf="Employee.length !== 0">

  <span class="mat-headline">Employee List</span>

  <table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8" >

    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> User ID </th>
      <td mat-cell *matCellDef="let element"> {{element.id}} </td>
    </ng-container>


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


    <ng-container matColumnDef="email">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Email </th>
      <td mat-cell *matCellDef="let element"> {{element.email}} </td>
    </ng-container>


    <ng-container matColumnDef="phone">
      <th mat-header-cell *matHeaderCellDef> Phone </th>
      <td mat-cell *matCellDef="let element"> {{element.phone}} </td>
    </ng-container>

    <ng-container matColumnDef="actions">
      <th mat-header-cell *matHeaderCellDef> Actions </th>   
      <td mat-cell *matCellDef="let element"> 
        <button mat-raised-button routerLink="/employee-edit/{{element.id}}" color="primary"
        style="margin-right: 0.25rem;"><mat-icon>edit</mat-icon></button> 
        <button mat-raised-button (click)="deleteEmployee(element.id)" color="warn"><mat-icon>delete</mat-icon></button> 
      </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    <mat-paginator [pageSizeOptions]="[5,10,20]" showFirstLastButtons></mat-paginator>
  </table>
</div>

Ответы [ 2 ]

0 голосов
/ 06 марта 2020

Используйте сеттеры для решения проблемы

  @ViewChild(MatSort, { static: false })
  set sort(v: MatSort) {
   this.dataSource.sort = v;
  }

  @ViewChild(MatPaginator, { static: false })
  set paginator(v: MatPaginator) {
    this.dataSource.paginator = v;
  }
0 голосов
/ 06 марта 2020

Проблема в том, что когда вы визуализируете свой компонент, у вас есть это

*ngIf="Employee.length !== 0

, поэтому сейчас у вас ничего не будет в вашем представлении, пока ваше условие не станет истинным, и в этот раз ваше

 @ViewChild(MatSort, { static: true }) sort: MatSort;
 @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

пытается поймать сортировку и paginator из представления, но ваше представление не имеет ничего, потому что ваше условие в это время не соответствует действительности, поэтому, если вы попытаетесь удалить свое условие, все будет работать

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...