What is the best way to store a gridster-item in the database when it is resized or changed using a static function

Following some resize and drag actions on my dashboard, I aim to store the updated size and position of my altered widget in my MongoDB database. Even though the gridster library offers the ability to respond to draggable and resizable events, these events are static. This poses a challenge when attempting to save the new values using my database service since it cannot be utilized due to its static nature.

I employed Angular 6 and angular-gridster2 6.0.10 for this project.

Does anyone have any suggestions on how I can leverage the resize/drag events to persist my data?


Below is a snippet of the code (not executable as it has been condensed):

export class SheetContentComponent implements OnInit {

  constructor(protected databaseService: DatabaseService,
              private dataService: DataService,
              protected projectService: ProjectService) {
  }

  protected widgetType = WidgetType;
  protected project: Project;
  protected currentDashboardId: string;
  protected user: User;
  protected currentSheetId: string;
  protected widgetPosition: GridsterItem;
  protected currentWidgetId: string;

  protected dashboard: Array<GridsterItem>;

  ngOnInit(): void {

    this.options = {
      gridType: GridType.Fit,
      displayGrid: DisplayGrid.Always,
      compactType: CompactType.None,
      margin: 10,
      outerMargin: true,
      minCols: 50,
      maxCols: 200,
      minRows: 50,
      maxRows: 100,
      pushItems: true,
      pushDirections: {north: true, east: true, south: true, west: true},
      pushResizeItems: true,
      swap: true,
      draggable: {
        enabled: true,
        stop: function (event, $element, widget) {
          console.log("draggable");
          this.saveInDatabase($element.el.id, event, 'position');
        }
      },
      resizable: {
        enabled: true,
        stop: function (event, $element, widget) {
          console.log("resizable");
          this.saveInDatabase($element.el.id, event, 'position');
        }
      }
    };
  }


  /**
   * This method saves the selected options into the database.
   * @param widgetId the id of the widget to save
   * @param value the value
   * @param field the field where to store
   */
  protected saveInDatabase(widgetId: string, value, field: string): void {
    this.databaseService.updateDocument(this.databaseService.WIDGETSCOLLECTION, widgetId, new Fieldvalue(field, value))
      .subscribe(result => {
      }, error => {
        console.log('Error updating database entry ', error);
      });
  }
<gridster #dashboardgrid [options]="options" class="widget-container">
  <gridster-item *ngFor="let widget of list" id="widget.id" [id]="widget.id" [item]="widget.position" class="gridster-design" (mouseup)="enablePointer(widget.id)">
    <!-- more HTML stuff -->
  </gridster-item>
</gridster>

I am encountering the following error:

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

Answer №1

this is referred to as the current window instance when those function(s) are called. It is important to update your functions into arrow functions or bind to this. Make sure to do this whenever you define a callback function as function () {.... For example:

draggable: {
    enabled: true,
    stop: (event, $element, widget) => {
      console.log("dragable");
      this.saveInDatabase($element.el.id, event, 'position');
    }
  }
draggable: {
    enabled: true,
    stop: function (event, $element, widget) {
      console.log("dragable");
      this.saveInDatabase($element.el.id, event, 'position');
    }.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

Only the final defined document is instantiated by the Swagger-ui-express module

Currently, I am working on a Typescripted nodejs server and facing an issue with defining different swagger paths for separated controllers. The problem is that the swagger-ui-express module only displays the last defined document in the specific route. I ...

What is the simplest way to incorporate Vue with Typescript, without the need for a complex build setup?

I've been spending the last couple of days experimenting with my basic ASP.NET Core website set up for Typescript 2.9, but unfortunately, I haven't made much progress. My main goal is to keep the front-end simple, with just single Vue apps on eac ...

Tips for restricting a drag-drop container to only receive a single item in Angular Material's Drag-Drop functionality

Is there a way to restrict the drop container in @angular/cdk/drag-drop module (Angular Material Drag and Drop) to only accept one value instead of multiple values? I am working on a form where users can drag an image and drop it into a field that should o ...

Merge the variables extracted from an array of objects

I need to extract specific data from an array of objects and perform a calculation. For example, the provided data is as follows: const item = [{ "act": "Q", "line": 1, &quo ...

What method can I utilize to display a value that deviates from the one stored in the backend using Record?

Here is the HTML snippet that I am working with: <drop-down-list [name]="MeetingTool.Type" [options]="options$" [isRequired]="false" class="input-width" ...

Dealing with Angular 6 HTTP Interceptor and the frustrating net:: ERR_TIMED_OUT error

I have been puzzling over something recently that has left me scratching my head. Within my interceptor, there is code that deals with parsing and handling errors in specific ways based on factors such as status codes. While I haven't included this c ...

Angular application has the capability to dynamically load plugins without the need for recomp

As I work on developing the frontend of my Web Api (NET CORE) pluginable application, my goal is to utilize Angular 9. However, I must admit that I am not well-versed in this framework. In terms of my backend, it was crafted with extensibility in mind. At ...

Using Typescript and React to assign an array object to state

Here is the situation: const [state, setState] = useState({ menuCatalog: true, menuCommon: true, fetched_data: [] }); An example of data I am trying to set to the state property "fetched_data" looks like this: [{"id": 1, "name": "some_name", " ...

Error message: While running in JEST, the airtable code encountered a TypeError stating that it cannot read the 'bind' property of an

Encountered an error while running my Jest tests where there was an issue with importing Airtable TypeError: Cannot read property 'bind' of undefined > 1 | import AirtableAPI from 'airtable' | ^ at Object.&l ...

What is the best way to approach writing a shared value that is utilized across multiple files in Angular?

I am currently implementing Angular for the front end of my project. One challenge I'm facing is managing a single value, such as a 'role id', that needs to be used in multiple .ts files within Angular. Can anyone suggest an efficient way ...

Approach continuously activates database

The LanguageService class is injected into my components in order to retrieve translations for the component. When a key is not found in the Map, it fetches translations from the server and stores them in a Map. If the key is already in the Map, it retrie ...

Asynchronously download static images with the power of NextJS and TypeScript integration

I have a query regarding my website development using NextJS and TypeScript. The site features a showcase gallery and is completely static. Currently, the initial view shows thumbnails of images. When clicking on a thumbnail, the original image is display ...

Leveraging Angular 2 to retrieve information from mongoDB

I recently finished setting up my nodejs project which includes a database and some data. The database was created using the following URL: mongodb://localhost:27017/ Check out the code snippet below: var MongoClient = require('mongodb').MongoC ...

Getting the string value from an observable to set as the source attribute for an

I am facing an issue with my image service. It requires the user_id to retrieve the id of the user's profile picture, followed by another request to get the JPG image associated with that id. To fetch the image, use this code snippet: <img [src]=" ...

Steps for obtaining the current state array post re-ordering column in Angular datatables

I am facing an interesting scenario where I can successfully retrieve the current state of an array of columns using pure JS + jQuery, but unfortunately, the same approach does not seem to work in Angular 12! Despite going through the documentation for Ang ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...

"Exploring ways to effectively listen for actions in components or subscribe to state with ngrx

I have an object in the state that I initially set using an action and effect: { field1: 'value1', field2: 'value2', } Later on, I add a new field to this object after receiving a response from the server through effects. As a res ...

Unleashed Breakpoint Mystery in Ionic 5 Angular with VSCode

I recently upgraded my Ionic 5 Angular 12 app from Ionic 4 Angular 8. The application is working well and remains stable, but I have encountered some issues while debugging. Firstly, when I use the launch.json file in Visual Studio Code to run the app, it ...

Errors in TypeScript are being brought up by using if-else statements inside a loop

I am currently working on a function to retrieve referral codes from users. The user inputs a code, which is then checked against the database to see if it exists or not If the code provided matches the current user's code, it should not be accept ...

the behavior subject remains static and does not update

Working on setting my language in the BehaviorSubject with a default value using a LanguageService. The service structure is as follows import {Injectable} from '@angular/core'; import * as globals from '../../../environments/globals'; ...