前端Angular排序

前端Angular排序

此种方法适用于数据量小时,将数据全部获取后,在前端table中点击排序按钮进行排序。排序逻辑放在前端服务中,不需要向后端发请求。

创建服务SortTableListService提供排序方法

使用

1, Html中使用Ant Design of Angular的<nz-table>标签。

nzShowSort显示列的排序按钮,nzSortKey配置排序的依照属性名,sortlist()方法在点击排序按钮后调用。示例代码如下。

<nz-table #nzTable [nzData]="list" >

     <thead (nzSortChange)="sortlist($event)" nzSingleSort>

          <tr>

               <th id="Label" nzWidth="10%" nzShowSort  nzSortKey="title">名称</th>

          </tr>

     </thead>

     <tbody>

          <tr [class.selected-tr]="i === selectedOrderIndex" *ngFor="let item of nzTable.data; let i = index">

               <td class="overflow-td">{{item.title}}</td>

          </tr>

     </tbody>

</nz-table>

2,在component.ts中实现sortlist()方法

1)引入SortTableListService服务

constructor(

        private sortTableListService: SortTableListService

    ) {}

2)在sortlist()方法中调用服务方法实现排序。

sortlist(sort: { key: string; value: string }): void {

    if (this.isUndefinedOrNull(this.list)) {

         return;

    }

    this.list = this.sortTableListService.sortTableListBykey(sort, list);

  }

当table中的某一项是一个list拼接显示的值时

eg:<nz-table>中[nzData]的值 list : dto[]。
dto的属性包含subPropertyList: subDto[]。即dto中不仅包含object类型的属性,还包括list数组类型的属性。
subDto的属性包括siteName等。在table中展示siteName时拼接subPropertyList中的每一项。
若对siteName这一列进行排序,则需要调用SortTableListService的另一个方法sortTableListByKeyAndListkey().
示例代码如下:

html:

<nz-table #nzTable [nzData]="list" >

     <thead (nzSortChange)="sortlist($event)" nzSingleSort>

          <tr>

               <th id="Label" nzWidth="10%" nzShowSort  nzSortKey="title">名称</th>

               <th id="TreatmentSite" nzWidth="10%" nzShowSort  nzSortKey="siteName">治疗部位</th>

          </tr>

     </thead>

     <tbody>

          <tr [class.selected-tr]="i === selectedOrderIndex" *ngFor="let item of nzTable.data; let i = index"

               (click)="switchSelectedOrder(i)">

               <td class="overflow-td">{{item.title}}</td>

               <td class="overflow-td">

                    <div

                         *ngFor="let d of item?.subPropertyList; let i = index; let c = count;">

                         <div *ngIf="d.siteName != null">

                              {{d.siteName}}

                              <em *ngIf="i != c - 1"> / </em>

                         </div>

                    </div>

               </td>

          </tr>

     </tbody>

</nz-table>

component.ts

sortlist(sort: { key: string; value: string }): void {

        this.list =

         this.sortTableListService.sortTableListByKeyAndListkey(sort,

             this.list, ['siteName'], 'subPropertyList');

    }

SortTableListService

根据自己项目的情况注入该服务,示例中使用 providedIn: 'root'

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class SortTableListService {

     Init() {}

     // 列表中对象的属性不包含list属性,每个属性均为一个object
     // 通过列表中对象的某个属性进行排序, key为对象的属性名称,设置在在<th>中nzSortKey的值
     // sort为此次排序传入的排序参照属性名和排序顺序
     sortTableListBykey(sort: { key: string; value: string }, initiallist: any[]): any[] {
          if (sort.key && sort.value) {
              let list: any[] = [];
                  list = initiallist.sort((a, b) =>
                  sort.value === 'ascend' ?
                      (a[sort.key] > b[sort.key] ?
                          1 :
                          -1)
                      :
                      (b[sort.key] > a[sort.key] ?
                          1 :
                          -1)
              );
              initiallist = [...list];
          }
          return initiallist;
     }

     

     // 若列表中对象的某个属性也为list,页面展示为遍历属性list的对象属性值,进行拼接
     // lisProperty为列表对象中属性为list的属性名,key为list属性对象的属性名称,设置在在<th>中nzSortKey的值。
     // lisPropertyItem 为列表对象中属性为list的对象的属性名称。
     // eg:initiallist: dto[]; dto的属性有lisPropertyName: subDto[]; subDto的属性名为lisPropertyItem数组中的值
     sortTableListByKeyAndListkey(sort: { key: string; value: string },
         initiallist: any[], lisPropertyItem: string[], lisPropertyName: string): any[] {
          if (sort.key && sort.value) {
               let list: any[] = [];
               const isAscend = (sort.value === 'ascend');
               if (lisPropertyItem.includes(sort.key)) {
                    list = initiallist.sort((a, b) =>
                        this.compairObjectByListProperty(a, b, sort.key, isAscend, lisPropertyName) ? 1 : -1
                   );
                } else {
                    list = initiallist.sort((a, b) =>
                     this.compairObjectByProperty(a, b, sort.key, isAscend) ? 1 : -1
                    );
                }
                initiallist = [...list];
          }
          return initiallist;
      }

     private compairObjectByProperty(a: any, b: any, sortKey: string, isAscend: boolean): boolean {
          return isAscend ?
               (a[sortKey] > b[sortKey] ?
               true :
               false)
               :
               (b[sortKey] > a[sortKey] ?
               true :
               false)
      }

     private compairObjectByListProperty(a: any, b: any, sortKey: string,
         isAscend: boolean, lisPropertyName: string): boolean {
          if (this.isUndefinedOrNull(a[lisPropertyName])) {
               return isAscend ? false : true;
             }
             if (this.isUndefinedOrNull(b[lisPropertyName])) {
               return isAscend ? true : false;
             }
             let aValueListString = '';
             let bValueListString = '';
             a[lisPropertyName].forEach(item => {
                 if (!this.isUndefinedOrNull(item)) {
                     aValueListString += item[sortKey];
                 }
             })
             b[lisPropertyName].forEach(item => {
                 if (!this.isUndefinedOrNull(item)) {
                     bValueListString += item[sortKey];
                 }
             })
             return isAscend ?
              (aValueListString > bValueListString ? true : false)
              :
             (bValueListString > aValueListString ? true : false) ;
      }

      isUndefinedOrNull(object: any): boolean {
          if (object === undefined
            || object === null) {
              return true;
          }
          return false;
       }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular实现可编辑表格并具有提交功能需要以下步骤: 1. 安装必要的依赖项:使用以下命令安装所需的依赖项 ```bash npm install @angular/cdk --save npm install @angular/material --save ``` 2. 创建表格组件:创建一个新的组件,例如edit-table.component,在该组件中定义要在表格中显示的数据和表格结构。 3. 使用Angular Material中的mat-table组件:在edit-table.component中使用mat-table组件,该组件提供了一个可编辑的表格,并为我们提供了一些额外的功能,例如排序、筛选和分页等。 4. 使用mat-cell组件:使用mat-cell组件在表格中呈现要显示的数据。mat-cell组件允许我们使用Angular模板语法在表格中呈现动态数据。 5. 实现编辑功能:为了实现可编辑表格,我们需要在mat-cell组件上使用mat-form-field组件来包装单元格中的数据。mat-form-field组件提供了一个用于编辑单元格的输入框。 6. 实现提交功能:在该组件中创建一个按钮,当用户完成编辑并点击提交按钮时,将调用一个提交数据的方法。该方法将获取编辑后的数据并将其提交到服务器上。 以下是一个示例代码: ```html <!-- edit-table.component.html --> <button mat-raised-button (click)="submitData()">提交</button> <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef> 名称 </th> <td mat-cell *matCellDef="let element; let i = index;"> <mat-form-field> <input matInput [(ngModel)]="element.name"> </mat-form-field> </td> </ng-container> <ng-container matColumnDef="age"> <th mat-header-cell *matHeaderCellDef> 年龄 </th> <td mat-cell *matCellDef="let element; let i = index;"> <mat-form-field> <input matInput [(ngModel)]="element.age"> </mat-form-field> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> ``` ```typescript // edit-table.component.ts import { Component, OnInit } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; export interface Person { name: string; age: number; } @Component({ selector: 'app-edit-table', templateUrl: './edit-table.component.html', styleUrls: ['./edit-table.component.css'] }) export class EditTableComponent implements OnInit { displayedColumns: string[] = ['name', 'age']; dataSource: MatTableDataSource<Person>; constructor() { const people: Person[] = [ {name: '张三', age: 20}, {name: '李四', age: 30}, {name: '王五', age: 40} ]; this.dataSource = new MatTableDataSource(people); } ngOnInit(): void { } submitData(): void { const data = this.dataSource.data; console.log(data); // TODO: 将数据提交到服务器 } } ``` 以上代码示例中,我们使用Angular Material中的mat-table组件创建了一个可编辑的表格,并使用mat-cell组件在表格中呈现数据。我们还使用mat-form-field组件在单元格中提供编辑功能,并在提交按钮上调用submitData()方法来提交表格数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值