Never stop learning, approaching the AI
  • 😄About
  • 🅰️AI-Candy on YouTube
    • 🎬YouTube 视频列表
    • 💠AI项目本地部署
      • 1️⃣安装 Pytorch 运行环境
      • 2️⃣在Python虚拟环境下使用 VS Code or PyCharm
        • VS Code Python format
      • 3️⃣Create python virtual environment in Linux
    • 👽AI 入门系列课程
      • 0️向量及向量运算
        • Reshape array code
      • 1️人工智能,机器学习,深度学习 和神经网络的区别
      • 2️卷积神经网络(CNN)
        • 3D CNN sample code
      • 3️Transformer 原理
      • 4️前馈神经网络 (FNN)
  • 🎭Artificial intelligence
    • 1️⃣Deep learning / machine learning
      • 👉Deep Learning Resources
      • 👉Deep learning notes
    • 2️⃣Python
      • Youtube音乐下载
      • Pytorch 安装环境配置 (old)
        • TorchEEG
      • Anaconda3 Python path
      • Data
      • IEEE-754 Floating Point Converter
        • ieee 754 conversion function
      • 文件读写
      • 文本清理
      • Python 下载在线视频
      • 修改Jupyter Notebook 默认工作目录
    • 3️⃣AI Websites
  • 🪤Programming
    • SQL
      • Delete data and reset auto-increment ID
    • Angular
      • Angular-datatables, dd/MM/yyyy, sorting (no paged list)
      • Datatables save state using localStorage
      • Variable storage method
      • Colour picker
      • Error fix for click columns on Datatable
      • Auto address use Google place
      • Auto address use Azure Maps
      • Upload file to Server
      • Validators.required OnChange input
      • Date, Time field
      • VS Code: Auto add missing imports when save
      • Datatable setting
      • Date time format
      • sticky <th> and <td> content
      • Filter booked time
      • Dropdown time selection with interval
      • Angular date online test
      • Updating data without refreshing the page
      • Object array sort and sum
      • Multi-type of columns use in one column
      • Select button for datatables
      • Switch button and event
      • Delete column from Array
      • Three-layer structure
      • Remove shadow when print mat-dialog content
      • JSON Parse && Object Array
      • Detect unused import in Typescript
      • Change location using radio button
      • display multi line message in the Toastr
      • Custom LOCALE_ID
      • Batch add data from csv to API server
        • Angular read csv and upload to Server
      • USB Port reader Web solution
      • Debug Angular app using JavaScript Debugger in VS Code
      • Skills
        • FormData & FormGroup to JSON
        • Dropdown list (customer)
        • Get current datetime
        • Get first day of year, month, and date
        • Call a function in a forEach loop
        • disable and readonly
        • Form element value
        • HTML input type
        • Input pattern (validation)
      • Display pipe (UI format)
        • Input upper case and button checked
        • Icons (Bootstrap and CoreUI)
        • Page Refresh
        • Selection list (two ways)
        • onChange Selection event
        • Random Password and Toggle
        • Password match
        • Select checkbox disable
      • Print and save to PDF
      • Import JS into Angular
      • LocalStorage
      • Angular DataTable
        • Data sort
        • A sample usage
        • Angular DataTable server side big data query
      • Change chart.js chart type
      • Angular UI - .NET API - .NET Auth
      • Angular - .NET API
      • *ngIf else && change to @if
      • Angular add reCAPTCHA v3 (Google)
      • Angular update
        • Update from v13 to v15
        • Update from v15 to v18
      • Angular application version central
      • Face detection
        • Face-api.js
      • Angular, Node version compatibility matrix
      • Clear cache
      • Angular oauth2 OIDC
      • Angular add header
    • .NET Skills
      • Add ID manually
      • Auto Mapping
        • Ignore Nesting
        • Startup setting
        • Datetime processing in AutoMapping
        • AutoMapper example
      • Validation filter
      • BaseController
      • Group by many
      • Database first, scaffold to class
      • Log setting and exception handler
      • Update appsetting.json value
      • Azure service bus message (queue)
      • Read appsetting.json value
      • Auth get user info by email
      • Azure Time zone
      • .NET API Add Service
      • Object comparison
      • Coravel Schedule
        • Read appsettings.json
      • .Net Core RDLC Report, Coravel and Email
      • Check Network and SQL server connections.
      • Datatime custom format
      • Many to Many EF
        • Many to Many CheckBox
      • PDFpig: Send Email with PDF attachment
      • .NET Core Middleware order
      • .NET API add Worker Service
      • .NET Router
      • Partial columns update
      • Add and Delete
      • 图片自适应宽度
      • ASP.NET Identity
      • Upload file to Azure
        • Upload file to Blob
      • Developer Guide
      • Code first one-many
      • ASP.NET MVC 5 Custom Error Page
      • VS can't debug
      • 通过邮编查 NSW COVID-19 感染人数
      • Jquery File Upload
      • Jquery Datepicker
      • ajax delete file from server
      • Autofac in MVC
      • Autofac in .NET Core
      • .NET Core
      • HTTP Return code
      • IdentityServer4
    • Power BI
      • Add parameter to PowerBI report
      • Convert UTC to Local time
      • Python in PowerBI
        • IEEE-754 conversion
      • PowerBI embed app - Server
      • PowerBI embed app - Client
        • Setting on portal
    • Azure service
      • Key Vault
      • Service bus - queue
      • Power Automate
      • Kusto Query Language
      • Azure Data Explorer
      • Reserved keyword on Azure Error
      • SQL Azure time convert
    • Azure blob
      • Azure blob setting
      • Display image from Blob
      • Upload image to Blob through .NET API
    • Html Bootstrap Icon, colour, size
      • Html spacing
      • Html text alignment
    • Video stream - JsMpeg
      • SSL - generate key
      • Client (SSL)
      • Websocket-Server (SSL)
      • Play RTSP video stream
    • ⏰Time Zone
      • datetime-local set date range
      • 🕐Get data by local time (UI, API)
      • 🕑Add offset hours for local UI and report
      • 🕒UTC time and Datetime convert
      • 🕓Angular - Timezone selection
      • 🕔Angular - Convert UTC to local time
      • 🕕C# Time Zone
  • >>>>>>>>>>>>>>>>>>>>>>>>>>>>
  • 🪜Apps and Skills
    • 1️Windows system app skills
      • Brother HL-2130 打印机 Toner 报警
      • VS Code 快捷键
      • Check SHA256 on windows
      • blob 视频下载
      • Photoshop 制作证件照片
      • 获取 Windows Key
      • 10进制36进制互转
      • Error when publish to Azure
      • Disable windows automatic update
      • Outlook setup for Yahoo Email
      • IIS setting
      • Windows 8/10, IIS Service
      • 安装程序出错 2052,2053 报警
      • 6 Yao Chinese UI
    • 2️Linux command
    • 3️Git command
    • 4️Bitbucket
    • 5️Gitbook Skills
    • 6️GitHub Desktop
    • 7️⃣EndNote
      • EndNote V21
      • Endnote使用技巧
      • 批量删除/修改Endnote 中 notes 栏内容
  • Android mobile connect PC
  • 💎USEFUL LINKS
    • 1️Coding websites
      • Website links
    • 2️Windows 平台工具,网站
    • 3️PotPlayer 设置
  • >>>>>>>>>>>>>>>>>>>>>>>>>>>>
  • 🚩Research >>EEG
    • 1️EEG基本知识的理论介绍
      • EEG 简介
      • EEG 的节律信号
      • EEG电极帽
      • EEG 伪迹
      • ERP 介绍
      • ERP 成分
      • EEG 数据分析软件
    • 2️LSL 应用
    • 3️EEG公开数据集汇总整理
    • 4️REDCap
      • Migration (Export & Import)
    • 5️⃣ScaneR
  • ☕Buy me a coffee
Powered by GitBook
On this page

Was this helpful?

  1. Programming
  2. Angular
  3. Angular DataTable

Angular DataTable server side big data query

Get data by paged list: 1. Angular Datatable Server Side Query, 2. .Net Core

├── @types/datatables.net-buttons@1.4.7 ├── @types/datatables.net@1.10.21 ├── angular-datatables@13.0.1 ├── datatables.net-buttons-dt@2.2.2 ├── datatables.net-buttons@2.2.2 ├── datatables.net-dt@1.12.1 ├── datatables.net-staterestore-dt@1.1.1 ├── datatables.net@1.11.4

// Html
	<div align="right" class="pb-1" >
	  <div class="controls" *ngIf="isLoading">
		<mat-progress-bar mode="indeterminate" color="primary" aria-label="Loading content"> </mat-progress-bar>
	  </div>
	</div>
	<div class="container-fluid h-100">
	  <table id ="recordtable" class="table table-bordered table-striped table-hover" datatable [dtOptions]="dtOptions"
		 style="width:100%">
		<thead class="table-dark">
		  <tr align="center" class="align-middle center">
			<th>Tech Name</th>
			<th>Customer</th>
			<th>Job No</th>
			<th>Record No</th>

		  </tr>
		</thead>
		<tbody>
		  <tr *ngFor="let dataItem of RecordList" scope="row">
			<td>{{dataItem.techName}}</td>
			<td>{{dataItem.customerName}}</td>
			<td>{{dataItem.jobNo}}</td>
			<td><span class="badge bg-info" > {{dataItem.natano}} </span></td>
		  </tr>
		</tbody>
	  </table>
	</div>
// Component.ts
 buildDtOptions() {
    ///https://datatables.net/reference/option/dom
   // var colSettings = [];
    this.dtOptions = {
      scrollY: 750,
      scrollX: true,
      scrollCollapse: true,
      order: [[0, 'desc']],
      ordering: true,
      pagingType: 'full_numbers',
      pageLength: 20,
      processing: true,
      autoWidth: false,
      lengthMenu: [
        [10, 20, 50, 100, 1000, -1],
        [10, 20, 50, 100, 1000, 'All'],
      ],
      columnDefs: [
        {
          width: "auto",
          targets: [1],
          visible: false
        }],
      fixedColumns: true,
      stateSave: true,
      dom: 'Blfrtip',
      buttons: [
        {
          extend: 'createState',
          config: {
            creationModal: true,
            toggle: {
              columns: {
                search: true,
                visible: true
              },
              length: true,
              order: true,
              paging: true,
              scroller: true,
              search: true,
              searchBuilder: true,
              searchPanes: true,
              select: true
            }
          }
        },
        'savedStates',
        'removeAllStates',
        'colvis',
        'copy', 'csv', 'pdf', 'excel','print',
      ],
      serverSide: true,
      responsive: true,

      ajax: (dtParameters: any, callback: any) => {
        this.isLoading = true;
        this.weighingService.getDataTablesDataPagedList(dtParameters)
          .pipe(
            finalize(() => {
              this.isLoading = false;
            })
          )
          .subscribe({
            next: resp => {
               callback({
                recordsTotal: resp.recordsTotal,
                recordsFiltered: resp.recordsFiltered,
                data: resp.data  // set data
              });
              this.isLoading = false;
            },
            error: error => {
              this.toastr.error(error)
            }
          });

      },
      columns: [
        { data: 'no' },
        { data: 'customer' },
        { data: 'amount' },
        { data: 'rego' },
        { data: 'status' },
        { data: 'timestamp' },
      ],

    };

  }
// Service.ts

	//dtParameters: DataTablesOptions
	public getDataTablesDataPagedList(dtParameters: any): Observable<DataTableResponse> {
	const body=JSON.stringify(dtParameters);
	const headers = { 'Content-Type': 'application/json'};
	return this.httpClient.post<DataTableResponse>(this.rootURL + 'api/natarecord/pagelist', body,{ headers}).pipe(map(res => res));
	}
// Model

	export class DataTableResponse {
		data!: any[];
		draw!: number;
		recordsFiltered!: number;
		recordsTotal!: number;
	}
// angular.json
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/scss/styles.scss",

              "node_modules/ngx-toastr/toastr.css",
              "node_modules/datatables.net-dt/css/jquery.dataTables.min.css",
              "node_modules/datatables.net-buttons-dt/css/buttons.dataTables.min.css",
              "node_modules/datatables.net-staterestore-dt/css/stateRestore.dataTables.min.css"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/jszip/dist/jszip.js",
              "node_modules/datatables.net/js/jquery.dataTables.min.js",
              "node_modules/datatables.net-buttons/js/dataTables.buttons.min.js",
              "node_modules/datatables.net-buttons/js/buttons.colVis.min.js",
              "node_modules/datatables.net-buttons/js/buttons.flash.min.js",
              "node_modules/datatables.net-buttons/js/buttons.html5.min.js",
              "node_modules/datatables.net-buttons/js/buttons.print.min.js",
              "node_modules/datatables.net-staterestore/js/dataTables.stateRestore.min.js"
            ],
// .Net Core Page Service

	public class PagedList<T> : List<T>
	{
		public int CurrentPage { get; private set; }
		public int TotalPages { get; private set; }
		public int PageSize { get; private set; }
		public int TotalCount { get; private set; }

		public bool HasPrevious => CurrentPage > 1;
		public bool HasNext => CurrentPage < TotalPages;

		public PagedList(List<T> items, int count, int pageNumber, int pageSize)
		{
			TotalCount = count;
			PageSize = pageSize;
			CurrentPage = pageNumber;
			TotalPages = (int)Math.Ceiling(count / (double)pageSize);

			AddRange(items);
		}

		public static PagedList<T> ToPagedList(IQueryable<T> source, int pageNumber, int pageSize)
		{
			var count = source.Count();
			var items = source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();

			return new PagedList<T>(items, count, pageNumber, pageSize);
		}
	}
// .Net Core Page Model

    public class PageParameters  
    {
        public int Draw { get; set; }
        public List<Column> Columns { get; set; }
        public List<Order> Order { get; set; }
        public int Start { get; set; }
        public int Length { get; set; }
        public Search Search { get; set; }
        public string SearchText => Search.Value ?? "";
    }

    public class Order
    {
        [JsonPropertyName("column")]
        public int Column { get; set; }

        [JsonPropertyName("dir")]
        public string Dir { get; set; }
    }

    public class Column
    {
        [JsonPropertyName("data")]
        public string Data { get; set; }

        [JsonPropertyName("name")]
        public string Name { get; set; }

        [JsonPropertyName("searchable")]
        public bool Searchable { get; set; }

        [JsonPropertyName("orderable")]
        public bool Orderable { get; set; }

        [JsonPropertyName("search")]
        public Search Search { get; set; }
    }

    public class DataTableResponse<T>
    {
        public List<T> Data { get; set; }
        public int draw { get; set; }
        public int recordsFiltered { get; set; }
        public int recordsTotal { get; set; }
    }
// .Net Core Page Controlar

	[HttpPost]
	[Route("api/natarecord/pagelist/{pageParameters?}")]
	public IActionResult GetPagelist([FromBody] PageParameters pageParameters)
 //   public  Task<ActionResult<IEnumerable<RecordViewModel>>> GetPagelist([FromBody] PageParameters pageParameters)
	{
		var records =  _repo.GetRecords(pageParameters);
		_logger.LogDebug($"Returned {records.TotalCount} records from database.");

		var result = _mapper.Map<List<RecordViewModel>>(records);

		DataTableResponse<RecordViewModel> dataResponse = new DataTableResponse<RecordViewModel>();
		dataResponse.Data = result;
		dataResponse.recordsTotal = records.TotalCount;
		dataResponse.recordsFiltered = records.TotalCount;

		return Ok(dataResponse);
	}
// .Net Core Page Repository

	//pagelist
	public PagedList<NATARecord> GetRecords(PageParameters pageParameters)
	{
		return PagedList<NATARecord>.ToPagedList(FindAll()
			.Where(x => x.CustomerName.Contains(pageParameters.SearchText) || x.JobNo.Contains(pageParameters.SearchText) || x.TechName.Contains(pageParameters.SearchText))
			.OrderByDescending(x => x.Id),
			pageParameters.Draw,
			pageParameters.Length);
	}
	
			//pagelist
	private IQueryable<Weighing> FindAll()
	{
		return this._context.Set<Weighing>()
			.AsNoTracking();
	}
PreviousA sample usageNextChange chart.js chart type

Last updated 1 year ago

Was this helpful?

🪤