В моем приложении Angular (с использованием Angular Material) у меня есть несколько таблиц.
Странно то, что в одном случае сортировка работает, а в другом - нет.
Вот таблица, которая работает:
<table mat-table [dataSource] = "dataSource" matSort>
<ng-container matColumnDef = "id">
<th mat-header-cell *matHeaderCellDef> ID </th>
<td mat-cell *matCellDef = "let row"> {{row.id}} </td>
</ng-container>
<ng-container matColumnDef = "firstName">
<th mat-header-cell *matHeaderCellDef mat-sort-header> First Name </th>
<td mat-cell *matCellDef = "let row"> {{row.firstName}} </td>
</ng-container>
<ng-container matColumnDef = "lastName">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Last Name </th>
<td mat-cell *matCellDef = "let row"> {{row.lastName}} </td>
</ng-container>
<ng-container matColumnDef = "viewProfile">
<th mat-header-cell *matHeaderCellDef class = "viewProfile"> Profile </th>
<td mat-cell *matCellDef = "let row" class = "viewProfile">
<button mat-icon-button (click) = "openProfile(row.id)">
<mat-icon aria-label = "icon-button with a page-view icon">pageview</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef = "displayedColumns"></tr>
<tr mat-row *matRowDef = "let row; columns: displayedColumns;"></tr>
</table>
... а вот таблица, которая не работает:
<table class = "table2" mat-table [dataSource] = "dataSource2" matSort>
<ng-container matColumnDef = "name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Project </th>
<td mat-cell *matCellDef = "let row"> {{row.name}} </td>
</ng-container>
<ng-container matColumnDef = "role">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Role </th>
<td mat-cell *matCellDef = "let row"> {{row.role}} </td>
</ng-container>
<ng-container matColumnDef = "beginning">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Beginning </th>
<td mat-cell *matCellDef = "let row"> {{row.beginning | date : "mediumDate"}} </td>
</ng-container>
<ng-container matColumnDef = "end">
<th mat-header-cell *matHeaderCellDef mat-sort-header> End </th>
<td mat-cell *matCellDef = "let row"> {{row.end | date : "mediumDate"}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef = "displayedColumns2"></tr>
<tr mat-row *matRowDef = "let row; columns: displayedColumns2;"></tr>
</table>
Как видите, в обоих случаях я использую «matSort» (в теге table) и «mat-sort-header» (для столбцов, которые предполагается сортировать).
Кроме того, в каждом случае я делаю один и тот же импорт в файле component.ts:
import { MatTableDataSource, MatPaginator, MatSort, MatDialog } from '@angular/material';
Я просто не понимаю, почему сортировка работает в первом случае, а во втором - нет. У кого-нибудь есть идеи, что здесь происходит?
ваш источник данных поддерживает сортировку? Можете выложить plunkr?
Я использую Angular Material 6
источник данных во втором случае содержит помимо строк две даты ... может это быть причиной?





Вы уверены, что ваша вторая таблица (та, в которой сортировка не работает) не заключена в div с * ngIf? Поскольку это обычная проблема, как и при рендеринге шаблона, из-за * ngIf matSort не определен. Вот как это исправить: Сортировка таблицы данных материала Angular 5 не работает
Спасибо за предложенный ответ ... таблица заключена в несколько div, но ни один из этих div не имеет * ngIf
спасибо за предложенный ответ <3 Я использовал ngIf в тегах mat-table. Удалил после работ по сортировке :)
Убедитесь, что имя_столбца в массиве displayColumns,
displayedColumns = ['column_name'];
контейнер html,
ng-container matColumnDef = "column_name"
и ключи объектов dataSource,
dataSource = [ {"column_name": "value"} ];
ВСЕ МАТЧИ ИДЕАЛЬНО.
Это также может быть причиной того, что один набор данных не работает, а другие работают.
Я была такая же проблема. Это решение работает. Убедитесь, что имена столбцов и columnDef совпадают.
Есть еще одна возможная проблема. Помимо того, что имена столбцов должны соответствовать атрибуту matHeaderRowDef в строке mat-header-row * matHeaderRowDef, имя столбца также должно совпадать с именем поля класса / свойства типа содержимого, используемого в атрибуте dataSource.
например
<mat-table [dataSource] = "mySource" matSort>
<!-- modelViewFieldNameOne has to match the class field/property name! -->
<ng-container matColumnDef = "modelViewFieldNameOne">
<mat-header-cell *matHeaderCellDef
mat-sort-header>just a column</mat-header-cell>
<mat-cell *matCellDef = "let tableItem">{{ tableItem.getterForMyField }}</mat-cell>
</ng-container>
// typescript where 'mySource' is kept
mySource = new MatTableDataSource<MyModelViewType>();
// typescript of MyModelViewType
export class MyModelViewType{
// this is important, it has to match the ng-container matColumnDef attribute!!!
private modelViewFieldNameOne
// this getter naming is not important for mat-table attributes
public get getterForMyField(): string {
return this.modelViewFieldNameOne;
}
}
Моя таблица mat сортировалась нормально, пока тип представления модели (то есть MyModelViewType в приведенном выше примере) не был ре-факторизован, но изменилось только имя поля / свойства, имя getter () было сохранено, соответствующий столбец таблицы перестал правильно сортироваться. Как только атрибут совпадал с именем, он снова работал.
Я использую: @ angluar / cdk 9.2.2
Для данных, загружаемых с помощью вызова API:
Возможно, сортировка была установлена до того, как данные были загружены в таблицу; тем самым испортила функцию сортировки.
В этом случае измените:
** code to insert data into the table **
this.dataSource2.sort = this.sort;
К
** code to insert data into the table **
setTimeout(() => this.dataSource2.sort = this.sort, 2000); // Delay it by 2 seconds.
Где this.sort:
@ViewChild(MatSort, { static: false }) sort: MatSort;
Какую версию Angular Material вы используете?