如何解决为什么敏捷材料排序显示箭头但不对列进行排序?
我想使我的表可排序。 为此,我使用https://material.angular.io/components/sort/overview。 “排序标题”在Web应用程序的其他表中有效,我阅读了文档,观看了教程。.我不明白为什么在此特定组件中它不起作用...
-
matSort和mat-sort-header似乎位置合适,因为我在表中看到了箭头,可以单击但没有任何反应
-
import { MatSortModule } from '@angular/material/sort'
很好地导入了admin.module.ts -
组件,OnInit,ViewChild和MatSort可以很好地导入到user.component.ts
中 -
export class UserComponent implements OnInit
ngOnInit中的 -
this.dataSource.sort = this.sort;
@ViewChild(MatSort,{ static: true }) sort: MatSort;
中的有人帮我吗?
代码
user.component.ts:
import { Component,OnInit,ViewChild } from '@angular/core';
//[...]other imports
import { MatSort } from '@angular/material/sort';
@Component({
selector: 'app-user',templateUrl: './user.component.html',styleUrls: ['./user.component.less'],})
export class UserComponent implements OnInit {
public translatePage: ComponentsTrslt = ComponentsTrslt.PROFILE;
users: UserItem[] = []; // contains users get from back
public dataSource: MatTableDataSource<UserItem>; // users that will be displayed in a material way
public displayedColumns: string[] = [
'email','firstName','lastName','userRating','coreHour','action',]; // columns to display
public pageSize = 10; // default displayed elements number
public currentPage = 0; // default displayed page
public totalSize = 0; // default number of element in dataSource (not set yet)
@ViewChild(MatPaginator,{ static: false }) paginator: MatPaginator; // paginator at the bottom of the page
// sorted data
@ViewChild(MatSort,{ static: true }) sort: MatSort;
// [...] other code... : Popups / Dialog boxes + Edition data passed to forms / fields ...
constructor(
public translateService: TranslationService,private userService: UserService,private expertService: ExpertService,private clientService: ClientService,private router: Router,private snackBar: MatSnackBar,private formBuilder: FormBuilder,public dialog: MatDialog,public languageService: LanguageService
) {
}
ngOnInit(): void {
this.fetchAndMapUsers(); // include this.dataSource.sort = this.sort;
this.editExpertProfileForm = this.formBuilder.group({
lastName: '',firstName: '',email: '',phone: '',company: '',title: '',wage: '',citizenship: '',country: '',city: '',address: '',zipCode: '',rating: [{ value: null }],});
this.editProfileForm = this.formBuilder.group({
lastName: '',service: '',languages: [],});
this.editRatingForm = this.formBuilder.group({
id: '',userId: '',rating: '',available: '',});
this.editCoreHourForm = this.formBuilder.group({
coreHour: 0,});
}
// Get expert data from User Id
this.expertService.getByUserId(expertId).subscribe((data) => {
// Send data to form
this.editRatingForm.setValue({
id: data.id,userId: data.userId,rating: data.rating,});
this.expertInfoEdition = data;
this.expertRatingEdition = data.rating;
this.editModeRating = !this.editModeRating;
});
}
// Get all users from back
private fetchAndMapUsers(): void {
this.userService.getAll().subscribe((data) => {
console.log(data);
this.mapUsers(data); // include this.dataSource.sort = this.sort;
});
}
// populateTable() {
// this.userService.getAll()
// .subscribe(data => {
// this.results = data;
// this.dataSource = new MatTableDataSource(this.results);
// this.dataSource.sort = this.sort;
// })}
public handlePage(e: any) {
this.currentPage = e.pageIndex;
this.pageSize = e.pageSize;
this.iterator();
}
private iterator() {
const end = (this.currentPage + 1) * this.pageSize;
const start = this.currentPage * this.pageSize;
const part = this.users.slice(start,end);
this.dataSource = new MatTableDataSource<UserItem>(part);
}
// Create the list of users from the users got by the call to back
private mapUsers(data): void {
// Fill the list of users from the users got by the call to back
this.users = data.map((element) => {
const ui: UserItem = {
userId: element.id,email: element.email,firstName: element.firstName,lastName: element.lastName,isValidated: element.isValidated,isAdmin: element.isAdmin,isPremiumCommunity: element.isPremiumCommunity,hasCommunityAccess: element.hasCommunityAccess,userRating: null,coreHour: null,};
this.userService.get(element.id).subscribe((userData) => {
ui.coreHour = userData.creditsTimeRatio;
if (userData.expertId) {
this.expertService.get(userData.expertId).subscribe((expertData) => {
ui.userRating = expertData.rating;
});
}
});
if (!element.isDisabled) {
return ui;
}
});
// Sort by email address before displaying the list
this.users.sort((user1,user2) => {
if (user1.email < user2.email) {
return -1;
}
if (user1.email > user2.email) {
return 1;
}
return 0;
});
// setting datasource of table from users
this.dataSource = new MatTableDataSource<UserItem>(this.users);
this.dataSource.sort = this.sort;
console.log(' this.dataSource',this.dataSource); // return is ok and complete cf screenshot
this.dataSource.sortingDataAccessor = (
element: any,sortHeaderId: string
): string => {
if (typeof element[sortHeaderId] === 'string') {
return element[sortHeaderId].toLocaleLowerCase();
}
return element[sortHeaderId];
};
this.dataSource.paginator = this.paginator;
this.totalSize = this.users.length;
this.iterator();
}
// [...] + several functions : especially to update data
user.component.html:
<mat-table [dataSource]="this.dataSource" class="mat-elevation-z8" matSort>
<!-- E-Mail Column -->
<ng-container matColumnDef="email">
<mat-header-cell *matHeaderCellDef mat-sort-header>
E-Mail
</mat-header-cell>
<mat-cell *matCellDef="let element"> {{ element.email }} </mat-cell>
</ng-container>
<!-- First Name Column -->
<ng-container matColumnDef="firstName">
<mat-header-cell *matHeaderCellDef mat-sort-header>
First Name
</mat-header-cell>
<mat-cell *matCellDef="let element"> {{ element.firstName }} </mat-cell>
</ng-container>
<!-- Last Name Column -->
<ng-container matColumnDef="lastName">
<mat-header-cell *matHeaderCellDef mat-sort-header>
Last Name
</mat-header-cell>
<mat-cell *matCellDef="let element"> {{ element.lastName }} </mat-cell>
</ng-container>
<!-- Rating Column -->
<ng-container matColumnDef="userRating">
<mat-header-cell *matHeaderCellDef mat-sort-header>
Rating
</mat-header-cell>
<mat-cell *matCellDef="let element" class="ratingCell">
{{ element.userRating }}
<button
class="editRatingButton"
mat-button
color="stroked"
*ngIf="element.userRating"
matTooltip="Edit user rating"
(click)="OpClExRatingEdit(element.userId)"
>
Edit
</button>
</mat-cell>
</ng-container>
<!-- [...] etc... more or less the same template for all the others columns -->
</mat-table>
<mat-paginator
#paginator
[pageSize]="pageSize"
[pageSizeOptions]="[5,10,100]"
[showFirstLastButtons]="true"
[length]="totalSize"
[pageIndex]="currentPage"
(page)="handlePage($event)"
></mat-paginator>
<!--some edit pop up-->
<div class="editPopup" *ngIf="editModeExpert">
<mat-card>
<form>
<!-- [...] -->
</form>
</mat-card>
</div>
<div class="editPopup" *ngIf="editModeClient">
<mat-card>
<form>
<!-- [...] -->
</form>
</mat-card>
</div>
<div class="editRatingPopup" *ngIf="editModeRating">
<mat-card>
<form>
<!-- [...] -->
</form>
</mat-card>
</div>
user-item.ts:
export interface UserItem {
email: string;
firstName: string;
lastName: string;
userId: string;
isValidated: boolean;
isAdmin: boolean;
hasCommunityAccess: boolean;
isPremiumCommunity: boolean;
userRating: number;
coreHour: number;
}
控制台日志屏幕截图: enter image description here 谢谢!
解决方法
[已解决]
1 /排序失败,因为(我没看到...)'this.dataSource'也已在其他函数中设置:请参见下文
private iterator() {
const end = (this.currentPage + 1) * this.pageSize;
const start = this.currentPage * this.pageSize;
const part = this.users.slice(start,end);
// this.dataSource = new MatTableDataSource<UserItem>(part); // init dataSource here create a bugg for the table's sorting
}
2 /我遇到的其他铅。在另一个表中。当我单击排序箭头时,这在我的单元格中创建了新表...很奇怪,我表中的单元格完全混乱了。 好吧,解决方案:
在 x.component.ts 中,更改“触发器”:
由以下人员控制:
trigger('detailExpand',[
state('collapsed',style({ height: '0px',minHeight: '0',display: 'none' })),state('expanded',style({ height: '*' })),transition('expanded <=> collapsed',animate('225ms cubic-bezier(0.4,0.0,0.2,1)')),])
尝试:
trigger('detailExpand',[
state('collapsed,void',transition('expanded <=> void',1)'))
])
(在github.com上找到解决方案)
希望它将对某人有帮助...!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。