Leverage external libraries in Angular

I discovered a library that I want to incorporate into my app: https://www.npmjs.com/package/jquery-animated-headlines

However, I am struggling with the process of importing it.

Firstly, I have added these lines in my angular-cli.json:

"styles": [
    ...
    "../node_modules/jquery-animated-headlines/dist/css/jquery.animatedheadline.css"
  ],
  "scripts": [
    ...
    "../node_modules/jquery-animated-headlines/dist/js/jquery.animatedheadline.min.js"
  ]

Secondly, I installed jQuery using npm install jquery --save

Next, I imported jQuery like this: import * as $ from 'jquery';

Finally, when copying and pasting their example code, I encountered an issue:

TS :

constructor () {
   $(function() {
     $('.selector').animatedHeadline();
   })
}

HTML :

<div class="selector">
  <h1 class="ah-headline">
    <span>My favorite food is</span>
    <span class="ah-words-wrapper">
        <b class="is-visible">pizza</b>
        <b>sushi</b>
        <b>steak</b>
    </span>
  </h1>
</div>

The error message I received was:

Uncaught TypeError: $(...).animatedHeadline is not a function

If anyone could offer guidance on where I may be going wrong, it would be greatly appreciated. Thank you!

Answer №1

To add your libraries in Angular, you can simply import them where they are needed without including them in angular.json.

Start by installing the required packages:

npm install jquery jquery-animated-headlines --save

Next, navigate to the component where you want to use them and import:

import * as $ from 'jquery' // If not imported globally.
import * as animatedHeadline from 'jquery-animated-headlines;


@Component()
...
constructor () {
    $(document).ready(() => $('.selector').animatedHeadline())
}

Answer №2

I managed to make it work with the following steps, although I believe there is room for improvement. Initially, I set up a new project using @angular/cli version 6.

npm install --save jquery jquery-animated-headlines

Next, in the angular.json file, I included

"node_modules/jquery-animated-headlines/dist/css/jquery.animatedheadline.css"
in the styles array.

Then, I updated the content of app.component.html to:

<h2 #foo>Here are some links to help you start: </h2>

Included code from app.component.ts:

import { Component, AfterContentInit, ViewChild, ElementRef } from '@angular/core';

import * as jQuery from 'jquery';
import 'jquery-animated-headlines';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
  @ViewChild('foo') fooElement: ElementRef<any>;

  ngAfterContentInit(): void {
    $(this.fooElement.nativeElement).animatedHeadline();
  }
}

Although things appeared to be working at this point, they didn't due to how the plugin library was written. I needed to manually update the import of jquery in the

node_modules/jquery-animated-headlines/dist/js/jquery.animatedhealdine.js
file.

The original code looked like this:

(function($) {
  .
  .
  .
}(jQuery));

I modified it to:

(function (factory) {
    "use strict";
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    }
    else if(typeof module !== 'undefined' && module.exports) {
        module.exports = factory(require('jquery'));
    }
    else {
        factory(jQuery);
    }
}(function ($, undefined) {
  .
  .
}));

While this solution may not be ideal and might not integrate smoothly with an automated build system, it should suffice for local development purposes.

UPDATE:

To implement this in your application, follow these steps:

Add the following entries to the scripts property in the angular.json file:

"node_modules/jquery/dist/jquery.js",
"node_modules/jquery-animated-headlines/dist/js/jquery.animatedheadline.js"

In your component, declare var $: any;. For instance:

import { Component, AfterContentInit, ViewChild, ElementRef } from '@angular/core';

declare var $: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
  @ViewChild('foo') fooElement: ElementRef<any>;

  ngAfterContentInit(): void {
    $(this.fooElement.nativeElement).animatedHeadline();
  }
}

Check out the GitHub repo for more details.

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 steps can I take to resolve the race condition in my JQuery Multiselect?

I have implemented Eric Hynd's amazing multiselect plugin to populate two dropdown menus. The first dropdown is for business units: ... $('#lbBusinessUnits').multiselect({ height: "auto", selectedList: 20 }); ... The second dropdown is fo ...

What is the best method to save changes made in a webdatagrid to a session?

My goal is to set the datasource of a grid to a session variable, bind it, and then add a row or rows to the dataset and save the changes back to the session. However, I am encountering an issue after trying to commit the changes, resulting in an AJAX sync ...

The PUT method is not supported when using the $.ajax function with Internet Explorer 11

Currently, on the edit page, an API controller is being utilized. Here is the code block for $.ajax: var settings = {}; settings.baseUri = '@Request.ApplicationPath'; var infoGetUrl = ""; if (settings.baseUri === "/ServerProjectName") { inf ...

Utilizing static arrays in jquery-tokeninput

When passing a static array to jQuery token input, I encountered an issue where the search results are not exact matches due to the absence of server-side queries. For example, with an array ['aa','bab','aab','abb'] ...

Instructions for turning an HTML table cell into an editable text box

Essentially, I'm looking to enable users to click on the table and edit the text within it. I found inspiration from this Js Fiddle: http://jsfiddle.net/ddd3nick/ExA3j/22/ Below is the code I've compiled based on the JS fiddle reference. I tho ...

What is the method for retrieving the Java List containing custom class objects defined within the <s:iterator> tag in a JSP file from within my JavaScript function?

Within my jsp file, I am retrieving a List of objects from my java action class (struts2) and displaying them. Now, I need to access these list objects within my javascript method. How can I achieve this? The code in mycode.jsp: <script type="text/jav ...

Personalized jQuery calendar options

Seeking advice from experienced jQuery users! I am in search of a stylish and customizable jQuery calendar. Despite attempting the jQuery UI Date picker, I am struggling to adjust its CSS settings. Is there a superior alternative that allows for full CSS ...

ReactJS presents an issue where buttons on the navigation bar are not properly aligned

I am currently utilizing the navbar component from Bootstrap 5, and I've encountered a UI problem. What is my current setup? This is the existing structure of my navbar: https://i.sstatic.net/eETzd.png What is my desired outcome? I aim to have the n ...

The function .get() is expecting callback functions, however it received an undefined object at route.(anonymous function) as get[]

Hey everyone, I've encountered an error in my server.js file and being a beginner I'm struggling to find a solution. I've searched through numerous answers on Stack Overflow but haven't been able to resolve it. Can someone please help m ...

Updating the state on change for an array of objects: A step-by-step guide

In my current scenario, I have a state variable defined as: const [budget, setBudget] = React.useState<{ name: string; budget: number | null }[]>(); My goal is to update this state by using a TextField based on the name and value of each input ...

Leveraging components exported from a module

There is a UserService that is required by the UserModule and then added to the exports. import {Module} from '@nestjs/common' import {TypeOrmModule} from '@nestjs/typeorm' import {User} from './user.entity' import {UserServi ...

What is the best way to align HTML inputs within a grid, whether it be done automatically or manually using JavaScript?

Arrange 20 HTML inputs with various data types into grid-columns as the user inputs data. Ensure that the grid container has div elements correctly positioned for output. ...

Passing data from a form to JavaScript and then to PHP

I've been seeking assistance from another source for a similar issue, but I could really use some help to make this code function. My aim is to have the form send the "count" variable to JavaScript so it can execute a for loop a specific number of ti ...

The Google Maps listener event behaves as if it were clicked even though it is triggered by a mouseover

Two google.maps.event.addListener events are being added here google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) { markerIconAcademicCenter.url = 'MapIcons/Circle32.png' }); google.maps.event.addListener(markerAcade ...

What is the best way to extract numbers from a string using JavaScript?

I am working with a string in javascript that looks like this: var xyz= "M429,100L504.5,100L504.5,106L580,106L570,98M580,106L570,114"; My goal is to extract the numbers and store them in an array. I attempted the following code: var x=xyz.match(/\ ...

Displaying PDF Preview when Button is Clicked using Angular

Is there a way to preview a PDF using Base64 data? Here's the HTML code: And here's the TypeScript code: let file = new Blob([byte64String],{type:'application/pdf'}); this.pdfSourceUrl = URL.createObjectURL(file); When I try to prev ...

The connection named "default" was not located

Error ConnectionNotFoundError: Connection "default" was not found. I encountered this error when I implemented the dependency inversion principle in my project. ormconfig.json { "name": "default", "type": " ...

How to retrieve a MySQL column in Node.js using template literals

I have been trying to retrieve a field from MySQL in my Node.js file using template literals, but I am struggling to get the value. In my post.controller.js file, you can see where it says message: Post ${body.post_id} was successfully created, with post_i ...

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

Error: Typescript module cannot be found, resolution failed

Currently, I am working on a react + typescript application where I have developed a module containing interfaces that are utilized across various classes within my project. While my IDE is able to resolve these interfaces without any issues, webpack consi ...