What is the best way to inject Angular services into Tabulator JS?

I have been working on implementing a rowClick() function for a Tabulator table. This function is supposed to pass the row's data to a service.

import { Component, AfterViewInit } from '@angular/core';
import { FuzeUser } from 'src/app/models/fuze-user';
import { UserEditService } from 'src/app/services/user-edit.service';
import { UserService } from 'src/app/services/user.service';
import Tabulator from 'tabulator-tables';

@Component({
  selector: 'app-user-table',
  templateUrl: './user-table.component.html',
  styleUrls: ['./user-table.component.scss']
})
export class UserTableComponent implements AfterViewInit {

  tab = document.createElement('div');
  public tableName: string = 'fuze-user-table';
  private columns: any[] = [];
  private rows: any[] = [];
  table: Tabulator;
  public drawn: boolean = false;
  

  constructor(private userService: UserService, private userEditService: UserEditService) {
  }



  private drawTable(): void {
    this.table = new Tabulator(this.tab, {
      layout: "fitDataStretch",
      movableColumns: true,
      maxHeight:"485px",
      pagination: "local",
      paginationSize: 25,
      paginationSizeSelector: [25, 50, 100],
      selectable: true,
      selectableRangeMode: "click",
      data: this.rows,
      columns: this.columns,
      rowClick:function(e, id, data, row){
        this.userEditService.setUser(data);
      }
    });
    document.getElementById(`${this.tableName}`).appendChild(this.tab);
  }
}

The problem I encountered is that the service cannot be accessed within the rowClick() function due to the scope of "this" being limited to the Tabulator object.

I tried creating a separate function in my component class that calls this.userEditService.setUser and passing it as a method to Tabulator. However, this approach also failed because the method passed could not access the service scope.

import { Component, AfterViewInit } from '@angular/core';
import { FuzeUser } from 'src/app/models/fuze-user';
import { UserEditService } from 'src/app/services/user-edit.service';
import { UserService } from 'src/app/services/user.service';
import Tabulator from 'tabulator-tables';

@Component({
  selector: 'app-user-table',
  templateUrl: './user-table.component.html',
  styleUrls: ['./user-table.component.scss']
})
export class UserTableComponent implements AfterViewInit {

  tab = document.createElement('div');
  public tableName: string = 'fuze-user-table';
  private columns: any[] = [];
  private rows: any[] = [];
  table: Tabulator;
  public drawn: boolean = false;
  

  constructor(private userService: UserService, private userEditService: UserEditService) {
  }

  private setUser(data: FuzeUser){
    this.userEditService.setUser(data)
  }

  private drawTable(callback: (user: any) => void): void {
    this.table = new Tabulator(this.tab, {
      layout: "fitDataStretch",
      movableColumns: true,
      maxHeight:"485px",
      pagination: "local",
      paginationSize: 25,
      paginationSizeSelector: [25, 50, 100],
      selectable: true,
      selectableRangeMode: "click",
      data: this.rows,
      columns: this.columns,
      rowClick:function(e, id, data, row){
        callback(data);
      }
    });
    document.getElementById(`${this.tableName}`).appendChild(this.tab);
  }
}

I am seeking guidance on how to access my service from within the Tabulator object efficiently.

Answer №1

Retain a reference to the function and incorporate it into the Tabulator initialization

const customFunction = this.userEditService.setUser;

this.table = new Tabulator(this.tab, {
  layout: "fitDataStretch",
  ...
  rowClick:function(e, id, data, row){
    customFunction(data);
  }
});

UPDATE I noticed you attempted it. Is setUser() method reliant on something from userEditSerivce?

UPDATE2 Using an arrow function might solve the issue

const customFunction = this.userEditService.setUser;

this.table = new Tabulator(this.tab, {
  layout: "fitDataStretch",
    ...
    rowClick: (e, id, data, row) => {
      customFunction(data);
    }
  });

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 with data loaded dynamically using ajax and json, all without relying on jquery

I am looking to populate a few select menus using JSON data retrieved from my PHP script. Each select menu should display different values based on the selections made in the other menus. While I understand how to clear and fill a select menu using JavaScr ...

The issue of javascript Map not updating its state is causing a problem

I've encountered an issue where my components are not re-rendering with the updated state when using a map to store state. const storage = (set, get) => ({ items: new Map(), addItem: (key, item) => { set((state) => state.items ...

Tips for preventing multiple button clicks until the completion of the initial click event

I created a clock that tells the time every quarter as per the professor's request. However, there is an issue - when I click multiple times, the clock keeps telling the time repeatedly until the number of tellings matches the number of clicks. I thou ...

Tips for executing an npm command within a C# class library

I am currently developing a project in a class library. The main objective of this project is to execute a JavaScript project using an npm command through a method call in C#. The npm command to run the JavaScript project is: npm start The JavaScript ...

Tips for utilizing an npm package in conjunction with Hugo

I created a basic hugo site with the following command: hugo new site quickstart Within the layouts/_default/baseof.html file, I have included a JavaScript file named script.js. Inside script.js, the code looks like this: import $ from 'jquery' ...

JavaScript never forgets to validate the user input

Forgive me for my lack of experience, but I am new to this and seeking guidance. I am struggling to find a straightforward example on how to validate HTML input using JavaScript. Currently, I am working on a search function and need help in implementing ...

What is the solution to fixing the Vetur/Vuelidate issue where the error message "'validate' does not exist in type 'ComponentOptions<Vue [etc.]" is displayed?

QUERY: I'm facing an issue with error 'validations' does not exist in type 'ComponentOptions<Vue [etc.] when using Vetur with TypeScript installed in VSCode. How can I resolve this? CONTEXT: I integrated Vuelidate into a single-file ...

What is the best way to modify an array of objects that is within another array?

Here is the model I am working with: const mongoose = require("mongoose"); const supplierProduct = new mongoose.Schema( { _id: mongoose.Schema.Types.ObjectId, //convert id to normal form supplier_id: { type: String, ...

Determine the subtotal for a particular item using AngularJS

Is there a way to apply the sub total amount to a specific item only? Currently, in my stackblitz example, when I add a new item and change the quantity of that last item, all recently added items also get updated. I want to modify the "changeSubtotal()" ...

The functionality of the Angular Password Strength Extension Color appears to be malfunctioning

I recently integrated the @angular-material-extensions/password-strength extension into my project. I followed the showcase example provided on their website at However, I encountered an issue where the primary color was not displaying correctly. Only the ...

Ways to insert JSON information into a designated index within a different JSON file with the help of AngularJS

Here is the response in json format retrieved from the API: { "columnHeaders": [ { "columnName": "id", "columnType": "bigint", "columnLength": 0, "columnDisplayType": "INTEGER", "isCo ...

Steps to activate checkbox upon hyperlink visitation

Hey there, I'm having a bit of trouble with enabling my checkbox once the hyperlink has been visited. Despite clicking the link, the checkbox remains disabled. Can anyone provide some guidance on how to get this working correctly? <script src=" ...

Determine the generic type of the parent class based on the constructor of the child class

Below is a code snippet illustrating the issue at hand: class Parent<T = unknown> { constructor(private prop: T) {} getProp(): T { return this.prop; } } class Child extends Parent { constructor() { super({ ...

Extract all links from an external website

I'm attempting to extract all the URLs from a webpage using jQuery so that I can later use them with $.get(). If these URLs were located on the same page as the script, retrieving them would be easy by doing something like var links = document.getEle ...

Exploring the capabilities of a Vue.js component

I am currently facing some challenges while trying to test a Vue.js component. My main issue lies in setting a property for the component and verifying that it has been set correctly. For context, the module has been loaded with exports and the JavaScrip ...

Installing a node.js application on elastic beanstalk with express framework

I've been struggling with deploying my application to Elastic Beanstalk throughout the entire day. The project structure I have is as follows (a single page app built with React) dist/ index.html bundle.js package.json app.js I compress it into ...

Reorder the position of an item within an array

I have an XML data source that provides all the information needed for my Vue app. Everything is working smoothly except for one specific value. The issue lies in retrieving a date from an element, which is currently formatted as: ['2022-10-25'] ...

The specified type argument is not compatible with the ObservableInput<any> type

Struggling with an issue where the argument type (key:string) => Observable | PayloadType | is causing problems when trying to assign it to a parameter of type '(value: string, index: number) => ObersvableInput' return action$.pipe( fil ...

Transferring information using "this.$router.push" in Vue.js

I'm currently developing a restaurant review project using Django REST and Vue.js. To ensure uniqueness, I have adopted Google Place ID as the primary key for my restaurants. The project also incorporates Google Place Autocomplete functionality. The ...

Tips for preventing the text from changing within a textbox using the identical ng-model

I have similar forms with the following structure: <form ng-submit="addReply(x)" class="dd animated slideInDown" > <div class="form-group"> <text-angular ng-model="form.reply"></text-angular> ...