迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > Angular >

在 Angular 中对表格进行排序

作者:迹忆客 最近更新:2023/04/10 浏览次数:

网页是进行演示的好方法。 当涉及到准备统计数据、制作物品价格列表或物品分类时,我们通常需要制作一个表格来对这些列表进行排序。

我们可以按升序、降序等方式对表进行排序。现在让我们看看在 Angular 框架内创建具有排序功能的表的最佳方法。


使用 Angular Material 对表格进行排序

Angular 材质依赖项是每种 Angular 组件的首选库已不再是新闻; 我们将为此方法安装 Angular Material 库。

创建项目文件夹后,移动到终端中的项目文件夹并安装 Angular Material 依赖项:ng add @angular/material; 完成后,下一步就是使用 Angular Material-prepped 代码创建页面结构,用于排序表。

app.component.html 文件中,我们插入这些代码。

代码片段 app.component.html

<table mat-table [dataSource]="dataSource" matSort (matSortChange)="announceSortChange($event)"
  class="mat-elevation-z8">
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by number">
      No.
    </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by name">
      Name
    </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by weight">
      Weight
    </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>
  <ng-container matColumnDef="symbol">
    <th mat-header-cell *matHeaderCellDef mat-sort-header sortActionDescription="Sort by symbol">
      Symbol
    </th>
    <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

我们正在这个文件中设置表格结构,如标题、行和列。

接下来,我们转到 app.component.ts 文件来设置控制表格的代码; 我们将编写这些代码:

代码片段 app.component.ts

import { LiveAnnouncer } from '@angular/cdk/a11y';
import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { MatSort, Sort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
  { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
  { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
  { position: 5, name: 'Boron', weight: 10.811, symbol: 'B' },
  { position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C' },
  { position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N' },
  { position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O' },
  { position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F' },
  { position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne' },
];
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  title = 'sortone';
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource(ELEMENT_DATA);
  constructor(private _liveAnnouncer: LiveAnnouncer) { }
  @ViewChild(MatSort) sort: MatSort;
  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }
  announceSortChange(sortState: Sort) {
    if (sortState.direction) {
      this._liveAnnouncer.announce(`Sorted ${sortState.direction}ending`);
    } else {
      this._liveAnnouncer.announce('Sorting cleared');
    }
  }
}

首先,我们从 Angular Material 库中导入所需的模块; 然后,我们声明将在每个表头中的输入类型; 对于名称,我们声明类型为字符串,对于重量和位置,我们声明类型为数字。

然后我们以数组的形式在表中声明我们想要的数据; 接下来,我们开始使用 this.dataSource.sort 创建排序函数。

app.module.ts 文件是处理我们用于应用程序的模块和依赖项的模块,因此我们需要在此处导入依赖项。 该文件应如下所示。

代码片段 app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatTableModule } from '@angular/material/table';
import { FormsModule } from '@angular/forms';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { MatSortModule } from '@angular/material/sort';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatTableModule,
    FormsModule,
    DragDropModule,
    MatSortModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

没有 CSS 的页面的美观和位置在哪里? 只需将这一小段代码添加到 app.component.css 文件中,如下所示。

代码片段 app.component.css

table {
    width: 100%;
  }

  th.mat-sort-header-sorted {
    color: black;
  }

输出结果:

使用 Angular Material 对表格进行排序


使用 Bootstrap 对表格进行排序

Bootstrap 让程序员的生活更轻松; 在我们应该编写代码小说的地方,Bootstrap 帮助我们编写更简洁、功能更好的代码。

与 Angular Material 一样,我们同样会使用 ng add @ng-bootstrap/ng-bootstrap 在项目文件夹中安装 Bootstrap 库。 安装成功后,我们导航到 app.component.html 文件来编写这些代码。

代码片段 app.component.html

<h2>Sort Table with Bootstrap</h2>
<table class="table table-striped">
  <thead>
  <tr>
    <th scope="col">#</th>
    <th scope="col" sortable="name" (sort)="onSort($event)">Country</th>
    <th scope="col" sortable="area" (sort)="onSort($event)">Area</th>
    <th scope="col" sortable="population" (sort)="onSort($event)">Population</th>
  </tr>
  </thead>
  <tbody>
  <tr *ngFor="let country of countries">
    <th scope="row">{{ country.id }}</th>
    <td>
      <img [src]="'https://upload.wikimedia.org/wikipedia/commons/' + country.flag" class="me-2" style="width: 20px">
      {{ country.name }}
    </td>
    <td>{{ country.area | number }}</td>
    <td>{{ country.population | number }}</td>
  </tr>
  </tbody>
</table>

在这里我们创建表的结构和标题; 现在,我们需要前往 app.component.ts 文件编写代码以使表格正常运行。

该文件将如下所示。

代码片段 app.component.ts

import { Component, Directive, EventEmitter, Input, Output, QueryList, ViewChildren } from '@angular/core';

interface Country {
  id: number;
  name: string;
  flag: string;
  area: number;
  population: number;
}
const COUNTRIES: Country[] = [
  {
    id: 1,
    name: 'Russia',
    flag: 'f/f3/Flag_of_Russia.svg',
    area: 17075200,
    population: 146989754
  },
  {
    id: 2,
    name: 'Canada',
    flag: 'c/cf/Flag_of_Canada.svg',
    area: 9976140,
    population: 36624199
  },
  {
    id: 3,
    name: 'United States',
    flag: 'a/a4/Flag_of_the_United_States.svg',
    area: 9629091,
    population: 324459463
  },
  {
    id: 4,
    name: 'China',
    flag: 'f/fa/Flag_of_the_People%27s_Republic_of_China.svg',
    area: 9596960,
    population: 1409517397
  }
];

export type SortColumn = keyof Country | '';
export type SortDirection = 'asc' | 'desc' | '';
const rotate: {[key: string]: SortDirection} = { 'asc': 'desc', 'desc': '', '': 'asc' };
const compare = (v1: string | number, v2: string | number) => v1 < v2 ? -1 : v1 > v2 ? 1 : 0;
export interface SortEvent {
  column: SortColumn;
  direction: SortDirection;
}
@Directive({
  selector: 'th[sortable]',
  host: {
    '[class.asc]': 'direction === "asc"',
    '[class.desc]': 'direction === "desc"',
    '(click)': 'rotate()'
  }
})
export class NgbdSortableHeader {
  @Input() sortable: SortColumn = '';
  @Input() direction: SortDirection = '';
  @Output() sort = new EventEmitter<SortEvent>();
  rotate() {
    this.direction = rotate[this.direction];
    this.sort.emit({column: this.sortable, direction: this.direction});
  }
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'sortfive';
  countries = COUNTRIES;
  @ViewChildren(NgbdSortableHeader) headers!: QueryList<NgbdSortableHeader>;
  onSort({column, direction}: SortEvent) {
    this.headers.forEach(header => {
      if (header.sortable !== column) {
        header.direction = '';
      }
    });
    if (direction === '' || column === '') {
      this.countries = COUNTRIES;
    } else {
      this.countries = [...COUNTRIES].sort((a, b) => {
        const res = compare(a[column], b[column]);
        return direction === 'asc' ? res : -res;
      });
    }
  }
}

在这里,我们首先声明将在每个表中输入的数据类型,并且由于我们将从标题中对项目进行排序,因此我们需要将 NgbdSortableHeader 声明为导出类。

然后我们进入 app.module.ts 文件以导入我们从 ng-bootstrap 应用的必要模块。

代码片段 app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent, NgbdSortableHeader } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [
    AppComponent,NgbdSortableHeader
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgbModule,
    CommonModule
  ],
  exports: [AppComponent],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

输出结果:

使用 Bootstrap 对表格进行排序


使用 ng-model 对表格进行排序 这个例子是代码效率最高的,因为与上面的前两个利用应用程序文件夹的所有组件不同,这个例子只利用 index.html 文件,因为 ng-model 可以绑定 HTML 控件的值 到应用程序数据。 此外,您无需安装任何依赖项即可使用此方法。

创建项目文件夹后,我们进入 index.html 文件编写这些代码。

index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Sortfour</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <body>
    <div class="container">
        <div ng-app="myApp" ng-controller="namesCtrl" ng-init="IsReverse=false">
        Search: <input type="text" ng-model="test"><br>
        <table class="table table-hover table-bordered table-striped">
          <tr>
              <th ng-click="sort('Name')">Name
              <th ng-click="sort('Age')">Age
              <th ng-click="sort('Email')">Email
              <th>Actions</th>
          </tr>
          <tr ng-repeat="x in names | filter:test | orderBy:sortParam:IsReverse">
              <td>{{x.Name}}
              <td>{{x.Age}}
              <td>{{x.Email}}
              <td>
                <div class="btn-group">
                    <a class="btn btn-primary" href="#">EDIT</a>
                    <a class="btn btn-primary" href="#">DELETE</a>
                </div>
              </td>
          </tr>
          </table>

    </div>

    <script>
    angular.module('myApp', []).controller('namesCtrl', function($scope) {
        $scope.names = [
            {Name:'Manav',Age:'22',Email:'pandya.manav@gmail.com'},
            {Name:'Rahul',Age:'25',Email:'pnd.rahul@gmail.com'},
            {Name:'Rohan',Age:'28',Email:'pnd.rohan@gmail.com'},
            {Name:'Jinish',Age:'18',Email:'jinish@gmail.com'}
        ];
        $scope.sort = function(sortId) {
            $scope.sortParam =  sortId;
            if($scope.IsReverse)
            {
                $scope.IsReverse = false;
            }
            else
            {
                $scope.IsReverse = true;
            }
        };
    });
    </script>
    </body>
</body>
</html>

首先,我们创建了表。 然后我们添加了标题并使用 ng-click 函数使它们可点击,这样我们就可以根据标题对表格进行排序。

然后我们以数组的形式在表中创建了我们想要的数据,并在 $scope 函数中声明它; 这允许我们使用 $scope.sort 函数向它添加排序功能。

输出:

使用 ng-model 对表格进行排序


总结

由于 Angular 框架的灵活性,我们被各种优秀的选项宠坏了,可以帮助我们创建具有排序功能的表。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便