Setting up Datatable in Angular 2+ without relying on jQuery

I need assistance with initializing a datatable for a table that has a unique id. Can you provide guidance on the syntax to achieve this?

Here is an example of my table structure:

<table id="myDataTable">
       <thead>
          <tr>
           <th>Employee Id</th>
           <th>Employee Name</th>
           <th>Designation</th>
          </tr>
       </thead>
       <tbody>
          <tr>
            <td>123451</td>
            <td>Employee 1</td>
            <td>Senior Developer</td>
          </tr>

          <tr>
           <td>123452</td>
           <td>Employee 2</td>
           <td>Developer</td>
          </tr>
       </tbody>
    </table>

In my TypeScript file, I attempted the following code:

@ViewChild('myDataTable') myDataTable: ElementRef;

ngOnInit(){
  this.myDataTable.nativeElement.dataTable({
    pagingType : 'full_numbers'
  });
}

Unfortunately, this resulted in an error in the browser console:

"Cannot read property 'nativeElement' of undefined"

Is there an alternative approach to achieving this without using jQuery ($)?

Answer №1

JavaScript is not involved in this process.

When utilizing ElementRef, the element will be initialized during the AfterViewInit lifecycle event rather than in OnInit.

Substitute ngOnInit with ngAfterViewInit or include it in your code.

@ViewChild('myDataTable') myDataTable: ElementRef;

ngAfterViewInit () {
  this.myDataTable.nativeElement.dataTable({
    pagingType : 'full_numbers'
  });
}

Your template should also include a template variable for Angular to detect the element properly.

<table id="myDataTable" #myDataTable>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes inability for JavaScript to access a property?

My current coding project involves the usage of typescript decorators in the following way: function logParameter(target: any, key : string, index : number) { var metadataKey = `__log_${key}_parameters`; console.log(target); console.log(metadataKey ...

Supply a variety of contexts to ngIf

Consider this template example. I am creating a user context using the as syntax and want to pass it into the userTmpl. It seems like there is no direct way to pass context beyond what is specified in the ngIf condition, which in this case is the showUser ...

What methods can be used in Angular 2 to delete and update row data through HTTP calls?

I am currently working on implementing employee data manipulation functionalities in an Angular application. While I have successfully managed to add new data to the array, I am facing challenges with updating and deleting existing data. Could someone pro ...

How can I incorporate MS Teams call recording into my web platform?

Currently in the process of developing a web application using Angular. Successfully integrated video call functionality through Azure Communication. Looking to now incorporate MS Teams call recording feature. Seeking assistance with reference links and s ...

What is the process for importing a file with an .mts extension in a CJS-first project?

Here's a snippet from a fetchin.mts file: import type { RequestInfo, RequestInit, Response } from "node-fetch"; const importDynamic = new Function("modulePath", "return import(modulePath);") export async function fetch(u ...

Getting a "function is not defined" error in Angular 6 while using it within a nested function

I'm facing an issue related to typescript, where the following code is causing trouble: private loadTeams = function(){ let token = sessionStorage.getItem('token'); if(token !== undefined && token !== null && token ...

Accessing files from various directories within my project

I'm working on a project with 2 sources and I need to import a file from MyProject into nest-project-payment. Can you please guide me on how to do this? Here is the current file structure of my project: https://i.stack.imgur.com/KGKnp.png I attempt ...

Implement Php gettext functionality in Typescript

I have a keen interest in AngularJs 2, and I am planning to incorporate it into my upcoming project. I would like to integrate i18n with Php gettext. In a previous project, I utilized Php gettext by embedding Php within Javascript code as shown below: // ...

Is there a way to effortlessly update a translation file in Angular 6 using a user-friendly interface?

In my Angular 6 application, I am utilizing ngx-translate and have en.json and nb.json translation files in the assets folder. I've implemented a UI to modify the values of the translation keys, but I'm unsure how to save these changes back to th ...

Using TypeScript to ensure class parameter types without affecting properties

I am tasked with defining a schema for "operations" that will be used in my application. This schema must be easily extendable for other groups of "operations" and should include a dictionary of settings for each keyword. Eventually, a "generic caller" wi ...

The navigation menu items remain static until a manual refresh is performed

I am facing an issue with my Angular app's authentication system. The navmenu displays login, logout, and the username when a user is logged in. However, after logging in, the navbar does not update until the page is refreshed. I can't figure out ...

Encountering the ExpressionChangedAfterItHasBeenCheckedError message despite updating the property via the @Output event

Attempting to update a property on the parent component through an event in the child component has proved challenging. Research suggests that this can be achieved using @Output as it is the recommended method to transmit data from child component to pare ...

When attempting to update a document using the PUT method in the MEAN stack, no changes are being applied

My application is designed to perform CRUD operations, it's very simple. I'm trying to update the information of a book but it's not working. What should I change? Additionally, I'm encountering this error: core.js:6210 ERROR TypeError ...

The element is implicitly assigned an 'any' type as the expression of type 'string' is unable to be used as an index within the type '{...}'

Trying to improve my react app with TypeScript, but encountering issues when typing certain variables. Here's the error message I'm facing: TypeScript error in /Users/SignUpFields.tsx(66,9): Element implicitly has an 'any' type becaus ...

Require assistance in accurately assigning a date to a Date[] in Typescript Array without altering current elements

In my current code, I have a loop that verifies if a date is a holiday and then adds it to an array. The issue I'm facing is that whenever I assign a new element to the array, all previous data in the list gets updated to the latest element. Here&apos ...

Module Z encountered an unforeseen issue with the import of value X while utilizing the --aot flag

My application experiences significant slowness while loading in the browser (not to mention on mobile, taking 10-15 seconds). Even after running ng build --prod, the performance remains an issue. Attempting to address this with Angular CLI beta 16, I tri ...

Retrieve user roles from core in Angular prior to implementing a guard

Hey, I'm facing an issue with my app.module setup. I have implemented lazy loading to load the core module and store roles in the core component. Everything works fine when I navigate from one page to another with the role guard applied. However, when ...

Difficulty locating the module in Typescript/Javascript

Currently facing an issue while trying to incorporate a module called "request" into my Angular 2 Typescript project from here. Despite following the usual installation process with npm install --save request and also attempting typings install request -- ...

Error: Callstack Overflow encountered in TypeScript application

Here is the code snippet that triggers a Callstack Size Exceeded Error: declare var createjs:any; import {Animation} from '../animation'; import {Events} from 'ionic-angular'; import { Inject } from '@angular/core'; exp ...

Refresh the page when scss file is saved

Exploring Angular 2 with the official Quick start guide has been a fun learning experience. The development dependencies specified in the package.json file enable live reload function by saving html files. In addition to utilizing Gulp and live reloading ...