The attempt to integrate a jQuery plugin with Angular 5 (Typescript) was unsuccessful

I'm currently attempting to incorporate the following plugin: https://github.com/gridstack/gridstack.js into a brand new Angular 5 (Typescript) project, but I've encountered this particular error:

https://i.sstatic.net/UOibd.png

I've installed the jQuery library using the command: npm install gridstack

This is the code snippet I'm working with:

app.component.ts

import { Component, OnInit } from '@angular/core';

import * as $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  title = 'app';

    constructor() {}

  ngOnInit() {
    $(document).ready(function(){
      // This part works fine.
      $("button").click(function(){
        var div = $("div");
        div.animate({left: '100px'}, "slow");
        div.animate({fontSize: '5em'}, "slow");
      });

      // However, this part fails !!!
      $('.grid-stack').gridstack();

    });
  }
}

app.component.html

<div style="text-align:center">
  <h1>
    Hello World!
  </h1>

  <button>Start Animation</button>
  <div style="border:1px solid #555;border-radius:3px;color:white;background:#555;height:105px;width:260px;position:relative; margin-top:10px">jQuery</div>

<div class="grid-stack">
    <div class="grid-stack-item"
        data-gs-x="0" data-gs-y="0"
        data-gs-width="4" data-gs-height="2">
            <div class="grid-stack-item-content"></div>
    </div>
    <div class="grid-stack-item"
        data-gs-x="4" data-gs-y="0"
        data-gs-width="4" data-gs-height="4">
            <div class="grid-stack-item-content"></div>
    </div>
</div>


</div>

Check out the demo displaying the error here: https://stackblitz.com/edit/angular-1sidhl

Answer №1

Take a look at the solution below.

Within your component file:

    declare var $el: JQuery;  // Make sure to include this line in your code to declare $ as a variable.

    @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
     })
   export class AppComponent implements OnInit {

       ngOnInit() {
    $(document).ready(function(){

Give this approach a try.

Answer №2

To properly integrate gridstack functionality into your Angular project, you must add the gridstack JavaScript file to the scripts section of your .angular-cli.json configuration file:

"scripts":[
//Your other dependencies, such as jQuery
"../node_modules/gridstack/dist/gridstack.js",
//any additional dependencies
]

After adding the gridstack script, remember to stop and restart the ng serve command to apply the changes.

Answer №3

The solution was to replace the following line:

import * as $ from 'jquery';

With:

declare var $: any;

This adjustment resolved the issue.

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

Creating a dropdown menu that functions for 24 hours non-stop by utilizing the Array.from( Array(n) )

Struggling to make my code less dense, I'm looking for the best way to implement a dropdown menu that allows users to choose between options 1-24 while the array is nested within an object. Thoughts? I'm working on a chrome extension that genera ...

Alternative to the Javascript Delay Function

I am working on a loading screen for my webpage that will cover the entire screen for 10 seconds before transitioning into the main content, which ideally should have loaded during that time frame. Currently, the issue is that the delay function only disp ...

How to use attributes in Angular 2 when initializing a class constructor

Is there a way to transfer attributes from a parent component to the constructor of their child components in Angular 2? The process is halfway solved, with attributes being successfully passed to the view. /client/app.ts import {Component, View, bootst ...

Having trouble establishing a connection from regular JavaScript to a socket.io backend? Face the issue of connection closure before

As I attempt to link my client-side JavaScript with a backend websocket service utilizing socket.io, I encounter an issue. I am attempting to establish a connection to the socket.io server using the native WebSocket object: new WebSocket("wss://localhost ...

Mistakes in Compiling Typescript Code in Angular 2

Currently, I am utilizing Visual Studio 2017 for the development of an Angular 2 application with an Asp.Net Core WebApi backend. My guide through this process is the ASP.NET Core and Angular 2 Book authored by Valerio De Sanctis. Initially, everything was ...

Tips for displaying only the initial 15 characters of a text value

The content extracted from a .ts file is being displayed on the home.html page. I am aiming to display only the initial 15 characters followed by 3 dots (...). Despite my efforts, the following code snippet is not functioning as expected: home.html < ...

The function of <a> click="" is not compatible when using a tabindex of ''0''

Below is the code I am working with. Everything seems to work fine without adding tabindex, but when I include tabindex='0' and press enter after focusing on the element, it stops functioning properly. <a type='button' role='b ...

Steps to fix issues with Cross-Origin Read Blocking (CORB) preventing cross-origin responses and Cross Origin errors

var bodyFormData = new FormData(); bodyFormData.set("data", "C://Users//harshit.tDownloads\\weather.csv"); bodyFormData.set("type", "text-intent"); //axios.post("https://api.einstein.ai/v2/language/datasets/upload", axio ...

By pairing delay(0) with refCount(), we can achieve optimal efficiency

The refCount operator is discussed in this article. It explains the necessity of adding delay(0) to prevent unsubscription of observable A: import { Observable } from "rxjs/Observable"; const source = Observable.defer(() => Observable. ...

Implementing JavaScript: Grouping JSON Response by Date and Category in a Table

The API response provided below contains sample data. {"success":true,"transaction":[{"_id":"58efd5717ddda769f26793fc","transId":"Exp/04-17/17","trpId":"Trav/dfsd/04-17/12","tripId":"58efd4dc7ddda769f26793f8","userId":"58ac19eaec1e7e4628be6f01","expenseHe ...

The module '@angular/material' could not be located, please check for errors

An Issue Arises The module '@angular/material' cannot be located. In the file app.module.ts import { MaterialModule } from '@angular/material'; Find more information here: https://material.angular.io/guide/getting-started npm in ...

Can the MD-Toggle-Button be employed on a different element other than a button?

I've been attempting to utilize the material design button toggle on something other than a regular button by following the examples provided in the material documentation here: https://material.angular.io/components/button-toggle/overview. However, n ...

Universal in Angular is malfunctioning

As a newcomer to Angular 4, I am looking to create an Angular app that is SEO friendly and supports Angular Universal (with the --universal flag after ung new or ung init). I have successfully created an Angular Universal app. However, when running the p ...

Error reported: "require" identifier not found in Typescript. Issue identified in IONIC 3 development environment

Error Encountered in Typescript: Cannot Find the Name 'require' Location: C:/Users/me/project/src/pages/home/home.ts // Need to require the Twilio module and create a REST client const client = require('twilio')(accountSid, ...

Changing the date in an EditText field on Android Studio

Can someone assist me in updating an EditText with the selected date from a DatePicker as it changes? Here is my code: private View view; private Button next; private EditText birthday; private DatePicker datePicker; @Override public ...

Safari browser not triggering the ready function

Why does the "ready" function not work in Safari but works in Firefox, Internet Explorer, and Chrome? More information: JQuery.js is included in the parent page which is why it is not necessary to include it in my page. $(document).ready(function () { h ...

Create varying widths of lines on either side of a vector line using the HTML canvas

Currently, I am working on utilizing an html canvas to draw lines. The process is straightforward; however, I am faced with a new challenge. I want to draw two lines at the same coordinates but with different widths - one on the right side and one on the l ...

I'm facing some uncertainties with a couple of AngularJS code snippets

At my workplace, I am tasked with making modifications to an angularjs project. However, I find the code quite complex and challenging to fully comprehend: app.controller("complementsController", function($scope, $rootScope, $mdSidenav, $timeout, $localSt ...

The debugging functionality in WebStorm version 11.0.4 is currently experiencing problems. Users have reported receiving a warning message stating that the commands node --debug and node --debug-br

Specific warning message: Warning: node --debug and node --debug-brk are no longer supported. Please use node --inspect or node --inspect-brk instead. Node version: 8.9.3 Does anyone know of a workaround to enable seamless debugging in the IDE? Any a ...

How can I add divs to an HTML page with a Javascript animated background?

I am currently facing an issue with my JavaScript animated background, consisting of just 3 pictures. I am trying to display some Div elements on it with content inside. Here is the code snippet I have right now: In my CSS file, I have defined styles for ...