сортировка матов не работает должным образом в angular 8 - PullRequest
0 голосов
/ 08 января 2020

Я реализовал сортировку в mat-table в angular 8. Я ссылался на руководство по https://material.angular.io/components/sort/overview, но сортировка работает только для нескольких столбцов, таких как "id", " электронная почта »,« контактные данные »,« страна »и« отдел ». Ниже приведен код:

Home.component. html:

<div class="empdata">
    <h3>
        Employee List:
    </h3>

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

    <!--- Note that these columns can be defined in any order.
          The actual rendered columns are set as a property on the row definition" -->

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

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

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

    <!-- Email Column -->
    <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>

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

    <!--Country Column -->
    <ng-container matColumnDef="country">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Country </th>
        <td mat-cell *matCellDef="let element"> {{element.country}} </td>
      </ng-container>

    <!-- department Column -->
    <ng-container matColumnDef="department">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Department </th>
      <td mat-cell *matCellDef="let element"> {{element.deptName}} </td>
    </ng-container>

    <!-- Actions Column -->
    <ng-container matColumnDef="actions">
      <th mat-header-cell *matHeaderCellDef> Actions </th>
      <td mat-cell *matCellDef="let element">
        <button color="accent" (click)="update(element.id)" mat-raised-button>Update</button>&nbsp;&nbsp;
        <button color="accent" (click)="delete(element.id)" mat-raised-button>Delete</button>
      </td>
    </ng-container>

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


</div>

2. Home.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { EmployeeService } from '../employee.service';
import { Router } from '@angular/router';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { IEmployee } from '../employee';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  //public employees = [];
  public dataSource; //= new MatTableDataSource<IEmployee>();;
  @ViewChild(MatSort, {static: true}) sort: MatSort;
  displayedColumns: string[] = ['id', 'fname', 'lname', 'email', 'phone', 'country','department', 'actions'];

  constructor(private _empService: EmployeeService, private router: Router) { }

  ngOnInit() {

    this._empService.getEmployees().subscribe(
      data => {
        this.dataSource = new MatTableDataSource();
        this.dataSource.data = data;
        this.dataSource.sort = this.sort;
      }
    );

  }

  update(id){
    this.dataSource.data.forEach((emp) => {
      if( emp.id == id){
        this._empService.updateEmp = emp;
        // console.log("in if condition..")
        this.router.navigate(['register']);
      }
    }); 
  }

  delete(id){

    this._empService.deleteEmployee(id).subscribe(
      data => {
        console.log("Delete request is successful");
        this._empService.status = "deleted";
        this.router.navigate(['update-success']);
      }
    )
  }
}

Может кто-нибудь сказать мне, что я делаю неправильно?

1 Ответ

0 голосов
/ 08 января 2020

Пожалуйста, посмотрите на это:

По умолчанию MatTableDataSource сортирует с предположением, что имя отсортированного столбца соответствует имени свойства данных, которое отображает столбец.

(записано в документах)

, что означает в вашем коде ...

 <ng-container matColumnDef="fname">

это имя должно быть изменено на firstName для удовлетворения вышеприведенного. То же самое с фамилией.

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