"Implementing a jQuery plugin in Angular 7: A step-by-step

I recently began using a JavaScript plugin that utilizes jQuery to convert XML to JSON. You can find the plugin here.

Initially, this plugin worked smoothly within my older AngularJs application. However, after upgrading to Angular7, I am facing challenges while setting it up.

To include both jQuery and the plugin in the project, I added the following lines in the `angular.json` file:

script: [
  "node_modules/jquery/dist/jquery.slim.js", 
  "src/app/plugins/jquery.xml2json.js"  //Please note that I have rearranged the order of scripts
]

Following this setup, I attempted to use the plugin as shown below:

// app.component.ts
import * as $ from 'jquery'

export class AppComponent{
  myFunction() {
    let xmlDocument = "<tree>test</tree>";
    $.xml2json(xmlDocument);
  }
}

However, upon execution, I encountered the following error message:

_plugins_jquery_xml2json_js__WEBPACK_IMPORTED_MODULE_3__.xml2json is not a function

Can anyone provide guidance or suggestions on how to resolve this issue?

Answer №1

From my understanding, when you reference JavaScript files in the angular.json file, the angular compiler will combine them into one file based on the order they are listed in the Script array. In this specific instance, the content of

src/app/plugins/jquery.xml2json.js
will be included first, followed by the content of
node_modules/jquery/dist/jquery.slim.js
.

If you switch the positions of these items, please let me know if it resolves the issue.

I came across an NPM package that can convert XML to JSON which may be helpful for your situation: https://www.npmjs.com/package/ngx-xml2json

UPDATE I didn't realize you had already attempted @showdev's suggestion.

I have spent time investigating the problem but haven't found a solution yet. It seems like Angular is not loading jQuery properly as I consistently receive an undefined error.

If you consider using the NPM package I recommended earlier, it could potentially resolve the issue with jQuery loading correctly.

Answer №2

Success! Thanks to David's suggestion, I was able to find a solution. Since I can't mark a comment as the official answer, I'll share it here:

// app.component.ts
//import * as $ from 'jquery' <-old

declare let $: any;          
export class AppComponent{
  myFunction() {
    let xmlDocument = "<tree>test</tree>";
    $.xml2json(xmlDocument);
  }
}

Remember, the order of the script is crucial in this scenario.

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

How to retrieve a nested array element in JavaScript

Here is the Pastebin link of the index.html file for reference: http://pastebin.com/g8WpX6Wn (The file contains broken image links and no CSS styling). If you would like to access the entire project, you can download the zip file. I am currently working ...

jQuery Causing Issues with Jquery in WordPress

I successfully constructed the homepage for a website, and the category slider was functioning properly. However, after transferring the site to Wordpress and installing a layered slider plugin, the category slider stopped working. For reference, here is ...

Creating a personalized data filtering system for tables in Angular 6

I recently wanted to enhance my Angular code with a custom table filter. After conducting a web search, I stumbled upon this informative blog post: The implementation worked quite effectively and here is the snippet of the pipe code: import { Pipe, PipeT ...

Issues with Ajax Requests

The pending requests from the Post need to be completed. I was hoping to record the JSON body of the request that comes in. Everything works fine when using Postman, but for some reason the AJAX requests are not functioning properly. Code snippet for Node ...

AngularJS - Calculate multiple currencies

I need to calculate the product of a value and months. For the input value, I am utilizing a Jquery Plugin to apply a currency mask. Unfortunately, the calculations are not functioning properly with this plugin. My goal is to multiply the value, includin ...

Getting the most out of jQuery DataTables column sizing

In my .NET web application, I am utilizing jQuery DataTables. I am wondering how to set a maximum width for only one specific column while allowing all other columns to be auto sized, as they currently are in my table. UPDATE The issue with the DataTable ...

Is there a way to transfer the getJSON output into an input field?

I am attempting to fill out a form with the data from the most recent entry in my database using $.getJSON. Although the GET request successfully returns the JSON, I am struggling to populate the fields with the data. I am relatively new to this and seekin ...

The JavaScript operator that functions in a manner akin to the SQL "like"

I am working on a jQuery function that needs to perform like the "like" operator. Can anyone help me achieve this? Your assistance is greatly appreciated. The function currently only works if I search for the whole word, for example: var vsearch = "home" ...

Switching classes for rows upon hovering functions correctly for rows that have not been altered, though it does not function properly for rows that have been sorted

I have a script that behaves in the following way: When hovering over rows, the current row being hovered on has a class added to it called .sorting_1.... It works well.. However, if I click on a column header to sort the rows based on that column, then ...

Issue with accessing custom read/write location during runtime in ngx-translate HTTP loader

After logging in, I need to load JSON files and then download a file at a specific location using a custom HTTP loader (TranslateHttpLoader). The assets/i18n/ folder is not writable with fileSystemModule.knownFolders.currentApp(), so I tried using fileSyst ...

Avoid pressing on y mat-button-toogle

In my component, I have a button-toggle like this: <mat-button-toggle-group appearance="legacy"> <mat-button-toggle *ngFor="let session of sessionsArray!"> <fa-icon icon="calendar-alt"></fa-icon> ...

Encountering a snag when trying to grant notification permission in the Expo app

I am experiencing an issue with a simple code that previously asked for notification permissions. However, I am now encountering the following error: "Error: Encountered an exception while calling native method: Exception occurred while executing exp ...

Initiating Angular APP_INITIALIZERThe Angular APP_INITIALIZER

I am a newcomer to Angular and currently utilizing Angular6 for development purposes. I have a specific query regarding my app. Before the app initializes, I need to invoke three services that provide configurations required by the app. Let's refer to ...

Angular promise not triggering loop creation

I am encountering an issue with a particular function handleFileInput(file: any) { let promise = new Promise((resolve, reject) => { this.uploadFileDetails.push({ filename:this.FileName,filetype:this.FileType}); ... resolve(dat ...

Deliver a locally defined variable from a template to the parent component

Currently, I am facing a challenge in passing a local input from an input field present in a child component to a parent component. Let me provide you with an example to illustrate: // Exporting itemInput in the Parent component: itemInput: string; // Te ...

Using .getJSON and .each in Javascript can sometimes be inconsistent in their functionality

I encountered a perplexing issue that has left me stumped. I am dynamically populating data into an html <select></select>. However, upon refreshing the page, I noticed that sometimes the data loads successfully, but most of the time it does n ...

Executing HTTP requests within a loop using AngularJS 2

I have been exploring the functionality of the YouTube API, and I am facing an issue with getting the icons for the first 'n' videos. For this, I need to make a request for each video. My initial thought was to use a for loop to handle these requ ...

Invoke a function within a distinct context using a loop

I'm currently using a script where a function is called for each element on the page. It works fine when I make separate function calls, but if I try to call the function with a unique selector, it doesn't work as expected. Is there a way I can c ...

Information vanishes upon scrolling and toggling on the page

While working on creating a website, I came across a great template and decided to use it as inspiration. You can check out the template here. However, during the process, I encountered a common UI bug. When a user scrolls down the page, clicks on the "X ...

Testing an observable from a different service in Angular: Best practices

$loggedIn = new BehaviorSubject<boolean>(false); constructor(private authHttp: AuthenticatedHttp, private httpResponseHandlerService: HttpResponseHandlerService) { this.$loggedIn.next(!this.jwtHelper.isTokenExpired(this.getToken())); if (thi ...