为什么敏捷材料排序显示箭头但不对列进行排序?

如何解决为什么敏捷材料排序显示箭头但不对列进行排序?

我想使我的表可排序。 为此,我使用https://material.angular.io/components/sort/overview。 “排序标题”在Web应用程序的其他表中有效,我阅读了文档,观看了教程。.我不明白为什么在此特定组件中它不起作用...

  1. matSort和mat-sort-header似乎位置合适,因为我在表中看到了箭头,可以单击但没有任何反应

  2. import { MatSortModule } from '@angular/material/sort'很好地导入了admin.module.ts

  3. 组件,OnInit,ViewChild和MatSort可以很好地导入到user.component.ts

  4. @ViewChild(MatSort,{ static: true }) sort: MatSort; 中的
  5. export class UserComponent implements OnInit

  6. ngOnInit中的
  7. this.dataSource.sort = this.sort;

有人帮我吗?

代码

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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-