Incorporating JQuery Plugins into Angular 4 Apps

I am currently attempting to incorporate various jquery plugins, such as Magnific-Popup, into my Angular 4 application but encountering difficulties. I successfully installed jQuery using

npm install --save-dev @types/jquery
in the terminal, yet implementing the actual plugins proves challenging. Initially, I attempted:

@Component({
 selector: 'app-showcase',
 templateUrl: './showcase.component.html',
 styleUrls: ['./showcase.component.css']
 })
 export class ShowcaseComponent implements OnInit {
 @ViewChild("elementRef") elref2: ElementRef;

 constructor(private elRef: ElementRef) { }

 ngOnInit() {


  jQuery(this.elref2.nativeElement).magnificPopup();

  }

 ngAfterViewInit() {

  }

To have TypeScript acknowledge the magnificPopup() function, I imported scripts from the magnificPopup documentation into my index.html (placed at the bottom of the body tag). However, it appears that this approach is not functioning correctly, with Webstorm indicating "cannot resolve file jquery.magnific-popup.js". While loading the jquery.min script works fine, attempts to npm-install magnific-popup were unsuccessful. I also experimented with adding the script to the angular.JSON file, but without success.

Therefore, I seek guidance on properly installing and utilizing a third-party jQuery plugin like magnific-popup within my Angular 4 application.

Your assistance would be greatly appreciated. Thank you.

Answer №1

I am currently working on an Angular project and have found the need to incorporate a jQuery dependent plugin (nanoscroller). To achieve this, I utilize angular-cli for my build processes and have made adjustments to my angular-cli.json file within the "scripts" property:

 "scripts": [
        "../node_modules/jquery/dist/jquery.js",
        "../node_modules/nanoscroller/bin/javascripts/jquery.nanoscroller.js"
      ]

After adding the necessary scripts, I integrated the plugin into my project by following these steps:

import { AfterViewInit, Component, ElementRef, OnDestroy, Renderer, ViewChild } from "@angular/core";

declare var jQuery: any;

@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.scss"]
})
export class AppComponent implements AfterViewInit {
    layoutMenuScroller: HTMLDivElement;
    @ViewChild("layoutMenuScroller") layoutMenuScrollerViewChild: ElementRef;

    constructor() {

    }

    ngAfterViewInit() {
         this.layoutMenuScroller = <HTMLDivElement>this.layoutMenuScrollerViewChild.nativeElement;
        jQuery(this.layoutMenuScroller).nanoScroller({ flash: true });

    }
    //  additional code here..
}

If you are facing a similar scenario, you can consider implementing these steps in your own use-case.

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

Diagnosing issues with the socket.io event system in a Node.js backend and Angular frontend

To establish a basic event system within my Node backend for notifying clients (Angular application) of specific events (such as when a user changes their profile photo), I am utilizing the socket.io library in the backend and its corresponding 'ngx-s ...

When importing a React Component with styling into the pages folder, it fails to function properly

I created a component in my components directory with custom styling: // import Link from "next/link"; import {Link} from "react-scroll" export default function Navbar() { return ( <div className="fixed w-full h-[79px] fle ...

Encountering an error when utilizing the ForEach method

Encountering a problem with using forEach: I am receiving an error message stating "unhandledRejection: TypeError: data.forEach is not a function" Here is the solution I attempted: I converted the data into JSON format before using forEach const data = JS ...

Obtain the length of a sound file in .wav format

Can anyone suggest a way to incorporate a waveform or horizontal bar on a website that displays the duration of a WAV file in seconds using HTML text? For instance, for a 60-second WAV file: I'm open to any ideas. ...

What is the process for implementing a splash screen in VueJS?

Having trouble creating a splash screen (loading-screen) in Vue JS that fades away after a few seconds to reveal the default view? I've experimented with several approaches, but none seem to be working for me. The closest example I found is on CodePen ...

Error in HTML: Text variable is not displaying the number value

Currently, I am facing a challenge with my code. I have a variable named "Timer" that I want to increment by one and then display the number. However, I am unable to see the "Test Successful!" message displayed on the screen. Surprisingly, there are no e ...

Transfer the HTTP functionality to a separate service using Angular2 and TypeScript

Currently diving into learning Angular2 and TypeScript after years of using Angular 1.*. I have a top level component that has a property derived from a custom type created in another class. When ngOnInit() is triggered, it makes an HTTP call to a mock RES ...

What steps can be taken to safeguard the title of the document in the top window from being altered by any iframe or script?

My typical approach is to delete and redefine the title property like in the code snippet below: if (delete document.title) { Object.defineProperty(document, 'title', { get: getter, set: setter, enumerable: true, ...

Is it possible to include if else logic code within a catch statement?

There's a nagging feeling within me that having logic code within a catch statement is not the right approach. For example, my catch block currently looks like this: try{ // do some stuff that throws some unexpected errors } ...

Navigate effortlessly with our vertical multi-level menu - simply hover over an option to reveal the next level of

This particular image demonstrates a vertical menu that is expanded. I am looking to display only the parent tag initially and upon hovering, show the next level and so forth. function display_children($parent, $level, $categoryModel) { $result = $ca ...

Managing sorting operations carried out on the backend with NGRX

What is the most effective method for handling backend-side sorting of entities? When I add sorted items using an adapter, my state does not recognize the changes because the items themselves remain the same, but their positions in the array have shifted. ...

What is the best way to set up environments for Google App Engine (GAE

After developing a web app with server and client components, I decided to deploy it to Google Cloud using App Engine. Although the deployment process was successful, the main issue lies in the non-functioning env_variables that are crucial for the applic ...

Unable to access the variable field of MongoDB in JavaScript

I'm facing an issue while trying to loop through an array I retrieved from mongodb. It seems the array is treated as a single element, and here is the code snippet: const project = await Project.findOne({ embedId: inititalData.embedId }); console. ...

Steps to create full screen jQuery tabs with overflow scroll feature in the content

I am in the process of creating a responsive web design using jQuery tabs. My goal is to make one page of the website occupy the entire screen (100% height and width), have a fixed height for the div.ui-tabs-nav, and enable scrolling for the content of div ...

Loop through an icon in Angular 2 until a specific condition is met

Currently, I am in the process of developing my portfolio website using Angular 2 and I want to incorporate a skill matrix. For testing purposes, I am using a square provided by font-awesome as an example. <tbody *ngFor="let skill of skills"> <tr ...

The AJAX success callback is malfunctioning

Below is the snippet I'm utilizing to interact with my web API controller titled Owner. However, despite everything appearing correct, the success function isn't triggering. Any suggestions on what might be causing this issue? $.ajax({ ...

Encountering a 'Uncaught SyntaxError: Unexpected Token <' error when deploying Angular2 on Heroku with all external references

As I attempt to deploy my angular4 app on Heroku, I encounter errors with all the .js references linked from my .html. The errors I am facing are: 16:29:54.613 myapp.herokuapp.com/:1 Resource interpreted as Stylesheet but transferred with MIME type text/ ...

I attempted to use an `if` statement as my type guard, but TypeScript decided to overlook it

const datas = { a: { "0": 0, "1": 1 }, b: { "0": 0 } } function fetchValue (data:keyof typeof datas, prop: "0"|"1") { if(prop in datas[data]) { return da ...

Display the submission timestamp in Angular upon clicking the submit button

How can I capture the date and time when a user clicks the submit button in Angular? For example, if a form with name and email inputs is filled out and submitted, I want to display the date and time along with the name and email in a table. Here is some ...

Why does my page keep refreshing even after I close the model?

I am facing the following issues: 1- Whenever I try to close my model by clicking 'cancel', it causes the page to reload. 2- Clicking 'OK' does not send the 'DELETE' request to the server, nothing is received, and the page r ...