迹忆客 专注技术分享

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

Angular 中的数据表

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

我们将介绍如何使用数据表并将 JSON 响应转换为 Angular 中的数据表。


Angular 中的数据表

有一个预建的 angular-datatables 库,我们可以使用它在 Angular 中显示复杂的数据表。

我们可以使用以下命令轻松安装它:

# terminal
ng add angular-datatables

或者我们可以使用 npm 手动安装它:

# terminal
npm install jquery --save
npm install datatables.net --save
npm install datatables.net-dt --save
npm install angular-datatables --save
npm install @types/jquery --save-dev
npm install @types/datatables.net --save-dev

之后,我们需要将脚本和样式属性中的依赖项添加到 angular.json 文件中。

# angular
"projects": {
    "your-app-name": {
      "architect": {
        "build": {
          "options": {
            "styles": [
              "node_modules/datatables.net-dt/css/jquery.dataTables.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/datatables.net/js/jquery.dataTables.js"
            ],
            ...
          }
}

现在,我们需要在应用程序的适当级别导入 DataTablesModule

# angular
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";

import { DataTablesModule } from "angular-datatables";

import { AppComponent } from "./app.component";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, DataTablesModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

在 Angular 中将 JSON 转换为数据表

如果我们想将 JSON 响应转换为 DataTables,我们可以使用以下示例。

我们需要将以下代码添加到 app.component.ts

# angular
import { AfterViewInit, VERSION, Component, OnInit, ViewChild } from '@angular/core';
import { DataTableDirective } from 'angular-datatables';
import { Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import { HttpParams, HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit, AfterViewInit {
  version = 'Angular: v' + VERSION.full;
  @ViewChild(DataTableDirective)
  datatableElement: DataTableDirective;
  dtOptions: DataTables.Settings = {};
  persons: any = [];
  // We use this trigger because fetching the list of persons can be quite long,
  // thus we make sure the data gets fetched before rendering
  dtTrigger: Subject<any> = new Subject();

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    const dataUrl = 'https://raw.githubusercontent.com/Inventico-Sol/test-json/main/data.json';

    this.http.get(dataUrl)
      .subscribe(response => {
        setTimeout(() => {
          this.persons = response.data;
          console.log(response);
          // Calling the DT trigger to manually render the table
          this.dtTrigger.next();
        });
      });

  }

  ngAfterViewInit(): void {

    this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
      dtInstance.columns().every(function () {
        const that = this;
        $('input', this.footer()).on('keyup change', function () {
          if (that.search() !== this['value']) {
            that
              .search(this['value'])
              .draw();
          }
        });
      });
    });

  }
}

然后,我们必须将以下代码添加到 app.component.html

# angular
{{ version }}
<table
  datatable
  [dtOptions]="dtOptions"
  [dtTrigger]="dtTrigger"
  class="row-border hover"
>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Age</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let person of persons">
      <td>{{ person.id }}</td>
      <td>{{ person.name }}</td>
      <td>{{ person.age }}</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th><input type="text" placeholder="Search ID" name="search-id" /></th>
      <th>
        <input
          type="text"
          placeholder="Search first name"
          name="search-first-name"
        />
      </th>
      <th>
        <input
          type="text"
          placeholder="Search last name"
          name="search-last-name"
        />
      </th>
    </tr>
  </tfoot>
</table>

输出:

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便