Cannot Read Property 'data' of Undefined Datatables
Information tables were introduced to simplify the process of visualizing, group, querying, and sorting data. Normally, a table is only a tabular form of information and has nothing special about it. But a data table may offering multiple features, including data sorting, data querying, updating of data, pagination, printing, and data exports, and more.
Making use of a information table in a framework similar Angular, which makes constant updates to its codebase, presents a few complications:
- Deprecated code: Angular DataTables, which we volition be using for this article, doesn't support older versions of the Athwart CLI (Angular 8 and beneath). Even older versions of Node and npm utilise deprecated lawmaking and therefore cannot employ the service
- Configuration: Every developer will agree that some configurations can be a real pain, and information table configuration in Angular is no exception
What is Angular DataTables?
Angular DataTables is a library for building circuitous HTML tables that uses jQuery's DataTables plugin. It is configured to back up TypeScript and optimized for Angular ii+.
Angular DataTables will come up in handy when:
- You lot have a very large dataset coming in from one or more API endpoints
- Y'all need customized data sorting/filtering
- You need to export and print data from a table
Angular DataTables features can be broadly grouped into two sets: basic and advanced. From there, Angular DataTables likewise supports a number of extensions.
Basic features
- Straight loading of information using AJAX calls
- Options such as column rendering in your Athwart components
- Table rendering using the custom function
dtTrigger - Server-side processing (though y'all'll need to override the AJAX selection)
Avant-garde features
- Custom filtering, which covers filtering by numbers, strings, Booleans, etc.
- Individual column filtering, which sorts data by cavalcade
- Re-rendering of data tabular array
- Multiple tables can be displayed simultaneously
- Router links tin can be added in the Angular components, which tin can display a single case of data in a new folio
- Pipes are added in the data table to transform data to the format you want
Installing Angular DataTables
Let's at present dive into installing and using Athwart DataTables. To start, we volition install our Athwart application, then install DataTables into the application:
ng new athwart-datatable
When the Athwart installation is done, you tin can and then step into the directory in your concluding and install DataTables:
cd angular-datable ng add angular-datatables
This will add together jQuery and the DataTables plugin to your angular.json file and your awarding. When the installation is done, you can and so import your data table module in app.module.ts to utilize it globally beyond the application:
// src/app/app.module.ts import {DataTablesModule} from 'angular-datatables'; imports: [ BrowserModule, AppRoutingModule, DataTablesModule, ], Making an API call
We'll use the JSONPlaceholder API to populate our data tabular array with data to take Athwart DataTables for a spin.
To practise that, we will first take to add the HttpClient module in our app.module.ts file to make it attainable in our services for HTTP requests. We do and then by importing it and calling it in the imports array:
// src/app/app.module.ts import { HttpClientModule } from '@angular/common/http'; imports: [ BrowserModule, AppRoutingModule, DataTablesModule, HttpClientModule ], Creating an Angular service
We'll create an Athwart service that will communicate with our HTTP module to fetch information from our API. To generate the service, we'll run the below command in the terminal:
ng generate service services/users/users
This will create a new file directory in our src/app folder containing our users.services.ts file:
-| Users/ users.service.spec.ts users.services.ts
We can and then import our HttpClient in our users.service.ts file:
// src/app/services/users/users.service.ts import { HttpClient } from '@angular/mutual/http'; constructor(private http: HttpClient) { } Next, nosotros add our function, which volition get users from the API link:
users() { this.http.get('https://jsonplaceholder.typicode.com/users'); } Generating a component
After creating the service, we then generate a component with the proper name users, which will hold the data we get from the service nosotros merely created and brandish it in our HTML page. We'll also use the users component to create our data table and all the functionalities.
To create a component, merely run the following control:
ng generate component components/users
Consuming the API
In our users components, we volition consume the API data fetched from the service nosotros created and shop it in an assortment named allUsers:
import { UsersService } from '../../services/users/users.service'; export form UsersComponent implements OnInit { allUsers: whatsoever = []; constructor(private service: UsersService) { } ngOnInit(): void { this.users(); } users(): void { this.service .users() .subscribe((response: any) => { this.allUsers = response.data; }); } } And then we populate our users.component.html with our fetched users:
<div class="container"> <div form="card yard-v p-3"> <div course="carte du jour-body"> <table class="table tabular array-bordered table-striped table-hover"> <thead> <tr> <th>ID</th> <thursday>Proper noun</th> <thursday>Username</th> <thursday>Email</th> <th>Phone number</th> <th>Address</th> </tr> </thead> <tbody> <tr *ngFor="let user of allUsers"> <td>{{ user.id }}</td> <td>{{ user.proper noun }}</td> <td>{{ user.username }}</td> <td>{{ user.email }}</td> <td>{{ user.phone }}</td> <td>{{ user.address.street }}, {{ user.accost.city }}</td> </tr> </tbody> </tabular array> </div> </div> </div> Information technology volition display something like this:
At present that this is done, crack your fingers because nosotros're about to swoop into data table usage and manipulation! 😋
Adding our data table
Since we already added our data table module in app.module.ts, we won't have to import it in our component; nosotros only call it as a subject using rxjs:
// src/app/components/users/users.components.ts import {Subject} from 'rxjs'; ... export grade UsersComponent implements OnInit { dtOptions: DataTables.Settings = {}; dtTrigger: Subject<any> = new Subject<whatever>(); } Then we add our unsubscribe function to the Athwart OnDestroy module:
import { Component, OnInit, OnDestroy } from '@angular/cadre'; consign class UsersComponent implements OnInit, OnDestroy { ... } ngOnDestroy(): void { this.dtTrigger.unsubscribe(); } This will reset the data table every time we get out the folio attached to the component.
With that, we will at present add a data table to our users function and a users table in our component HTML:
users(): void { this.service .users() .subscribe((response: any) => { this.allUsers = response; // initiate our information table this.dtTrigger.side by side(); }); } <tabular array class="table tabular array-bordered table-striped table-hover" datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger"> ... </table>
Filtering and pagination take been added to the table, equally you can discover in the epitome below:
Custom filtering
There may be times when we wish to search data presented to the end user in our own way. Common examples include number range searches (in between two numbers) and date range searches. Athwart DataTables allows you to make those custom searches easily and effortlessly.
North.B., the documentation for custom filtering in Angular DataTables is faulty, mainly because of updates in TypeScript with Angular, and so follow my examples instead.
To initiate custom filtering, nosotros will offset import a @ViewChild decorator, which allows usa to inject into a component class references to elements used within its template:
import {Component, OnInit, OnDestroy, ViewChild} from '@angular/core'; Then, we import DataTableDirective in our component:
import {DataTableDirective} from 'angular-datatables'; We then reference our DataTableDirective and assign information technology to a new variable datatableElement. Later on that, we will create max and min variables, which will take the maximum and minimum numbers for our custom filtering.
Permit's begin with the referencing:
@ViewChild(DataTableDirective, {static: false}) datatableElement: any = DataTableDirective; min: any = 0; max: any = 0;
Next, we employ the custom function for filtering in our ngOnInit:
ngOnInit(): void { ... $.fn.dataTable.ext.search.button((settings: any, data: string[], dataIndex: any) => { const id = parseFloat(data[0]) || 0; // use data for the id column return (Number.isNaN(this.min) && Number.isNaN(this.max)) || (Number.isNaN(this.min) && id <= this.max) || (this.min <= id && Number.isNaN(this.max)) || (this.min <= id && id <= this.max); }); } This will go the max and min numbers, fetch the information, so update the information tabular array. Adjacent, nosotros create a function to filter the data table past id:
filterById(): void { this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => { dtInstance.draw(); }); } Now it restarts the data tabular array when nosotros go out the folio:
ngOnDestroy(): void { ... $.fn.dataTable.ext.search.pop(); } With all this done, we then update our users.components.html folio to initiate our filterById office:
<class (submit)="filterById()"> <characterization> Min <input type="number" proper name="min" id="min" [(ngModel)]="min" /> </characterization> <label> Max <input blazon="number" name="max" id="max" [(ngModel)]="max" /> </label> <push button class="btn btn-primary" type="submit">Filter past ID</button> </form> <br />
And that'southward it — nosotros tin apply custom filtering past id.
Buttons extension
As mentioned above, Angular DataTables supports a number of extensions, one of which is a buttons extension. The buttons extension allows united states to export and re-create our table data as a file. This is especially useful when nosotros want to share information without giving admission to the application.
To use the DataTables buttons extension, install its plugin using the below command:
# If you want to consign excel files npm install jszip --save # JS file npm install datatables.net-buttons --salve # CSS file npm install datatables.internet-buttons-dt --save # Typings npm install @types/datatables.net-buttons --save-dev
Then add the dependencies in the scripts and styles attributes:
{ "projects": { "your-app-proper noun": { "architect": { "build": { "options": { "styles": [ ... "node_modules/datatables.internet-buttons-dt/css/buttons.dataTables.css" ], "scripts": [ ... "node_modules/jszip/dist/jszip.js", "node_modules/datatables.net-buttons/js/dataTables.buttons.js", "node_modules/datatables.net-buttons/js/buttons.colVis.js", "node_modules/datatables.internet-buttons/js/buttons.flash.js", "node_modules/datatables.net-buttons/js/buttons.html5.js", "node_modules/datatables.cyberspace-buttons/js/buttons.print.js" ], ... } And then nosotros include the configurations in our ngOnInit:
ngOnInit(): void { this.dtOptions = { // Declare the employ of the extension in the dom parameter dom: 'Bfrtip', }; } And here's the upshot — the buttons Copy, Excel, CSV, and Print have been added:
There are many more options to choose from when it comes to customizing your data table. With a few tweaks, you tin can shape information technology to your specifications and it will come out perfect for whatever you're building.
Wrapping up
And with that, we've introduced Athwart DataTables and its features. Nosotros besides practical information technology to an application, used some of its features, and explored the buttons extension. I made a few modifications to the original documentation because of the updates in Angular TypeScript. I hope this tutorial gave y'all a uncomplicated and easy-to-follow breakdown of how to use Athwart DataTables in your Angular application.
Experience your Angular apps exactly how a user does
Debugging Athwart applications can be difficult, especially when users experience issues that are hard to reproduce. If you're interested in monitoring and tracking Angular state and actions for all of your users in production, attempt LogRocket.
https://logrocket.com/signup/
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens on your site including network requests, JavaScript errors, and much more. Instead of guessing why issues happen, you can amass and study on what land your application was in when an upshot occurred.
The LogRocket NgRx plugin logs Athwart country and actions to the LogRocket panel, giving you context effectually what led to an error, and what state the application was in when an result occurred.
Modernize how you debug your Angular apps - Outset monitoring for free.
Source: https://blog.logrocket.com/angular-datatables-feature-rich-tables/
0 Response to "Cannot Read Property 'data' of Undefined Datatables"
Post a Comment