Is seamless integration possible between Angular2 and jQuery plugins?

When attempting to integrate jQuery plugins with Angular 2, there are three distinct scenarios:

1. ONLOAD: Initializing the plugin on page load works smoothly with the following code snippet:

ngAfterViewChecked(){
    ...
    $('#somedatatable1').DataTable()
    ...
}

2. ONCLICK: Triggering the plugin on click involves fetching server-generated HTML (although it's recommended to transfer only data in JSON format) and feeding it into the page before initializing the DataTable plugin:

maincomponent.ts

clickDatatableParse(){
    this.http.get(this.jsonUrl)
        .map(res => res.json()) 
        .subscribe(
            data => { 
                this.data = data
            },
            err => console.log(err),
            () => console.log("fetched!")
        )
}

maincomponent.html

<div id="contents" [innerHTML]="data?.htmltable">

HTML output after parsing retrieved data:

<div id="contents">
    <div id="somedatatable2">
        ....
    </div>
</div>

The question here is: Where should "$('.somedatatable2').datatables();" be placed for proper functionality? The aim is to retrieve and parse everything fully before calling the jQuery plugin for it to work correctly.


3. ONCLICK SUBCOMPONENT: Activating a subcomponent upon clicking:

maincomponent.ts

clickDatatableParse(){
    this.http.get(this.jsonUrl)
        .map(res => res.json()) 
        .subscribe(
            data => { 
                this.data = data
            },
            err => console.log(err),
            () => console.log("fetched!")
        )
}

maincomponent.html

<div id="subcomponent" [htmldata]="data?.htmltable">

subcomponent.html

<div id="subcomponentbody" [innerHTML]="htmldata">
    ....
</div>

Parsed HTML output after data retrieval and parsing:

<div id="subcomponentbody">
    <div id="somedatatable3">
        ....
    </div>
</div>

subcomponent.ts

ngAfterViewChecked(){
    ...
    $('#somedatatable3').DataTable()
    ...
}

The question arises: Is initiating the plugin in the subcomponent via ngAfterViewChecked the preferred choice?


An additional question: What is the correct way to include a jQuery plugin? Importing the plugin using "import * as Datatables from 'jquery-datatables'" and then running "npm install jquery-datatables --save" followed by adding the plugin's CSS file into @Component styleUrls like ['datatables.css','main.css']. Does this method align with best practices?

Answer №1

Utilizing the ngAfterViewInit hook has proved to be very effective for me. However, an issue can occur when Angular starts manipulating the DOM. To address this issue, a simple workaround is to refresh the table every time Angular manipulates the DOM by invoking $("#sometable").DataTable()

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

"Can anyone provide guidance on how to initiate a css 3d animation by clicking a button

Currently, I am developing a folding hide/show animation that can be triggered using Javascript. If you would like to take a look at the code and see a working example, please visit this link: You can also view just the gist here: https://gist.github.com ...

Choose an alternative following the start-up phase

I have been searching for solutions on various platforms, including Stack Overflow, but nothing seems to work for me. I am struggling with selecting the first option after initializing the box because currently it is choosing a blank option that is not eve ...

Is it possible for a script with ignore_user_abort(true) to be halted by using the exit() function in PHP?

I've implemented a script that begins with: ignore_user_abort(true) This script is responsible for sending out emails. The reason for using ignore_user_abort(true) is because I'm accessing the page via AJAX, and there's a possibility that t ...

Preserve data on page even after refreshing in Angular

Upon opening my website, I expect to see "Finance/voucher" at the top. However, after refreshing the page, only "Finance" appears which is not what I want. I need it to always display "Finance/voucher" even after a page refresh. I have included all the r ...

Troubleshooting: Issues with jQuery JavaScript Modal Popup functionality within MVC framework

When I click on the "Comments" link, a modal popup opens up and displays the content as expected. Now onto my issue: In the first scenario, the desired outcome is achieved but some other code does not execute. In this case, when I place the "@section" ins ...

Searching for the index of an item in a PHP array using the inArray jQuery method

I came across this code snippet online that seems to achieve what I'm looking for: $(document).ready(function(){ var arrData = [ "j", "Q", "u", "e","r","y" ]; alert(jQuery.inArray("Q", arrData)); }); Now, I have an array generated from a ...

ES6: The attribute 'selected' is not found on the data type 'Object'

While attempting to convert the JS code from 'AMcharts4 codepen pre selecting areas' into ES6, I encountered an error. Error TS2339: Property 'selected' does not exist on type 'Object'. Here is the code snippet that I am l ...

What is the best method to grab the href attribute with jQuery?

<table class="table1"> <tbody> <tr class="tablerow1"> <td valign="top"> <strong> <a href="http://www.wineweb.com/scripts/wineryPg.cfm/11094/Aan-de-Doorns-Co%2Dop ...

Adding design to distinct element after clicking a button

Struggling with a JS/Jquery issue on my portfolio website, I admit that I am still just an average programmer. My portfolio website has five buttons, each representing a different project. For each project, there is a corresponding text description and an ...

Which version of Keycloak should I use with Keycloak-js 18.0.0 if my application is running on AngularJS 1.6.0?

When a user tries to log out from the GUI using the provided SIGNOUT button, the logout process fails and the user receives an error message stating 'Invalid parameter: redirect_uri'. Angular-js version: 1.6.0 keyCloak version: 18.0.0 ...

Can you specify the necessary import statement for CallableContext?

My Google Cloud function is simple and looks like this: import * as functions from 'firebase-functions'; var util = require('util') export const repeat = functions.https.onCall( function (data, context) { console.log(&apo ...

Use data attributes to automatically populate one form field with the information from another form field using jQuery

Within my Laravel 5 ecommerce website, I am attempting to automatically populate the values in the shipping_address form with the values from the billing_address form if the checkbox with name = same_as_billing is selected. I have been trying to utilize t ...

Discovering whether input field is currently in focus using jQuery

Does anyone know how to determine if an input tag in HTML has focus using jQuery? The keydown event will function for forms when input, image, etc. tags have focus. However, it will not work if the focus is on the form itself but not on any specific tags ...

Unable to render React component after updating its state

After successfully retrieving data from my API, React is failing to render the cards. export default function Subjects() { const userApi = useUserService(); const auth = useRecoilValue(AuthAtom); const [loading, setLoading] = React.useState<boolea ...

Adjust the size of the div to match its parent's size when resizing

Can a div be resized to match its parent's size on window resize? Here is the current HTML code: <div class="sliderContainer"> <div id="cyler"> <div class="cy1" style="background-image:url(images/Keggy_Banner_Ie.jpg); back ...

Troubleshooting a Missing Angular (8) Pipe Error in Your Ionic 4 Application

Despite seeing similar questions posted here, none have provided a solution to my issue. I believe I am implementing it correctly, but clearly something is not right. In the app I'm developing with Ionic 4, I need to add a key to a URL in a gallery. ...

The data type 'T' cannot be assigned to type 'T'

Having extensive experience as a javascript developer, I recently delved into learning C# as my first statically typed language. My upcoming project involves using TypeScript, so I've been refreshing my knowledge on it. Below is the code I have writt ...

Improving User Experience with HTML Form Currency Field: Automatically Formatting Currency to 2 Decimal Places and Setting Maximum Length

Hello there, I am currently facing an issue with the currency auto-formatting in a deposit field on my form. The formatting adds 2 decimal places (for example, when a user types 2500, the field displays 25.00). However, the script I wrote does not seem to ...

What is the best way to toggle the visibility of forms based on the select element with the use of jQuery and Bootstrap

I have set up a page with 5 different forms, each hidden within a div element using the Bootstrap class .d-none. At the top of the page, there is a select input. My goal is to create a function in jQuery that will hide all forms when an option is selected ...

Preventing page unloading by utilizing a modal window

I am working on a functionality to detect any changes in textareas on a page and prompt the user with a custom modal window before they navigate away without submitting. I want to give the user the option to either leave the page or stay and submit the dat ...