Leveraging the injectable service within the end callback function alongside interactJS

When using interactJS with Angular to enable drag and drop functionality for elements with the 'draggable' class, everything was working smoothly until I encountered an issue with using the injected service of the component in the callback function for end drag. Here's the code snippet that caused the problem:

ngOnInit() {
    interact('.draggable')
        .draggable({
            inertia: true,
            modifiers: [
                interact.modifiers.restrictRect({
                    restriction: 'parent',
                    endOnly: true
                })
            ],
            autoScroll: true,
            listeners: { move: this.dragMoveListener, end: this.stackForUndo }
        })
}


stackForUndo() {
// get current state of svg
    let current_state = document.getElementById("Logo").outerHTML;

    // clear redo stack
    this.menuService.redo = {}

    // get the previous saved actions
    let actions = { elements: [] };

    // if no action has been cached, initialise the localStorage undo element
    if (actions == undefined) {
      actions = { elements: [] };

      // save stringified empty action to localStorage
      this.menuService.undo = actions;
    }

    // add the current state of the svg
    if(actions.elements.length >= 5){
      actions.elements.shift();
    }
    actions.elements.push(current_state);
    this.menuService.undo = actions;
}

However, after performing a drag operation, I encountered an issue where I couldn't drop the element and received the following error message in the browser console:

Cannot read property menuService of undefined (in this.menuService.redo = {})

Answer №1

The main issue you are facing is that the context of stackForUndo was lost, and to resolve this I made sure to bind it to the component in the following way:

ngOnInit() {
    interact('.draggable')
        .draggable({
            inertia: true,
            modifiers: [
                interact.modifiers.restrictRect({
                    restriction: 'parent',
                    endOnly: true
                })
            ],
            autoScroll: true,
            listeners: { move: this.dragMoveListener, end: this.stackForUndo.bind(this) }
        })
}

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

Update the TemplateUrl according to the URL Parameters (GET)

I've created a basic Angular code snippet (test.component.ts) that retrieves a variable from GET parameters: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ select ...

Guide on creating a server-side middleware in Next.js

In my upcoming nextjs project, which is a monorepo with both frontend and backend components, I am in need of a middleware to intercept requests. This middleware will handle tasks such as authentication and other necessary controls for every API call. Alth ...

Executing a single insert statement in a TypeScript Express application using PostgreSQL is taking over 240 milliseconds to complete

Seeking assistance with optimizing a db insert operation test using mocha for a node.js express app that utilizes fp-ts and pg npm package. The tests run successfully, but the insert test is taking over 240 ms to complete. The database table has a maximum ...

Utilizing localstorage data in angular 2: A comprehensive guide

Is there a way to utilize data stored in localstorage for another component? This is what the localstorage service looks like: localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success, res: res.data })); I am inte ...

Ways to display an icon in Angular 10 only when it is hovered over

Just getting started with Angular and still learning the concepts. Trying to figure out how to show an icon only when it's hovered over. Can anyone assist me? Sorry, can't share the code because of company rules. The icons are for sorting and ...

Leveraging getStaticProps in Next.js

I am currently embarking on my inaugural Nextjs project, focused on developing a basic blog utilizing the JSON placeholder API. Strangely, I am encountering an issue where the prop "posts" is being perceived as undefined. Can anyone provide assistance with ...

Retrieve the predetermined value from the dropdown menu option

I currently have two classes with a mapping structure as follows: User *--------------------1 Sexe Users are listed in the file list-users.component.html. When selecting a user for modification, I am redirected to the modify-user.component.html B ...

Convert the date into a string format instead of a UTC string representation

I am currently working on a node.js project using TypeScript. In this project, I have a Slot class defined as follows: export class Slot { startTime: Date; constructor(_startTime: Date){ this.startTime = _startTime } } // Within a controller method ...

Troubleshooting issue of incorporating hintText in a TextField within a create-react-app-with-typescript

After recently downloading, installing, and running the create-react-app-with-typescript, I have been exploring different components. My latest experiment involved adding a TextField with hintText using the following code: import TextField from 'mate ...

Error message: The value of ngIf has been altered after it has been checked

I am encountering the ngIf value changed error in my code and I'm unsure of the correct solution. Below is the HTML snippet causing the issue: <div *ngIf="currentVlaue"> <div class="section-body"> <div cla ...

Tips on using Visual Studio Code to troubleshoot Angular 4 unit tests

I am working on an Angular 4 project with Material design in Visual Studio Code. The setup is done using angular/cli. Currently, I have been writing unit tests using Karma and Jasmine. However, when trying to debug the tests by setting breakpoints, it doe ...

p-menu fails to appear

I'm currently experimenting with Primeng and Angular 2 to put together a basic menu. Take a look at my code snippet: import {Component, OnInit} from '@angular/core'; import {Menu, MenuItem} from 'primeng/primeng'; @Component({ ...

Error: Unable to locate module - The specified file cannot be resolved when utilizing an external JavaScript library

I am currently integrating a WYSIWYG editor (TUI Editor) into my Angular2+ application. Since there is no official Angular wrapper available, I have decided to create my own based on an existing wrapper. Due to some installation issues with npm, I saved t ...

Transition from using ReactDOM.render in favor of asynchronous callback to utilize createRoot()

Is there a React 18 equivalent of this code available? How does it handle the asynchronous part? ReactDOM.render(chart, container, async () => { //code that styles some chart cells and adds cells to a worksheet via exceljs }) ...

Can Next.js accommodate server-side redirection with internationalization?

I'm working on a small Next.js app that has pages accessible only to logged in users. To manage the authenticated routes, I created an HOC (withAuth) that handles redirection on the server side to prevent page flashing on the client side. Everything i ...

What is the correct way to include an NPM package in a Plunker project?

Encountered an error while utilizing angular2-infinite-scroll. Attempting to replicate it in a plunkr. Experimented with using npmcdn, hence added this line in the index.html file: <script src="https://npmcdn.com/<a href="/cdn-cgi/l/email-protectio ...

Analyzing bundle files with Angular CLI output

Currently, I am utilizing Angular CLI to develop a production app by using the --prod switch. The resulting bundle is generated in the dist directory. Is there a method to determine which classes and functions have been included in the final bundle after ...

At first, Typescript generics make an inference but are ultimately specified

In my TypeScript code, I have defined a custom Logger class with specific options. The DefaultLevel type is created as a union of 'info' and 'error'. The LoggerOptions interface includes two generics, CustomLevels and Level, where Custo ...

The attribute 'nameFormControl' is not a valid property on the 'ContactComponent' component

Greetings, StackOverflow community! I'm currently working on an Angular + Node app and I've run into a major problem related to forms and validators in Material Angular. Right now, I'm facing an issue where the HTML component is not recogn ...

How can I utilize a filter or pipe to populate product categories onto screens within Ionic 2?

I am considering creating an Ionic 2 app with 6 pages, but I'm unsure whether to utilize a Pipe or a Filter for the individual category pages and how to implement the necessary code. Each category page should be able to display products from the "app ...