Function cannot be executed from the context menu

While working on my context menu, I encountered an issue trying to call a function.

getContextMenuItems(params) {
    console.log(params.node.data)
    var result = [

      {
        name: "Delete",
        action : function () { 
         this.deletePriceFactor(params.node.data);
        }
        ,
        cssClasses: ["redFont", "bold"]
      },
      {
        name: "Audit"
      }

    ]
      return result;
    }

 deletePriceFactor = (rowdata)  =>{
    this.priceFactorService.deleteEntry(rowdata.exchangeCode, rowdata.productCode, rowdata.secType).subscribe(pricefactors => {
    });

  }

Despite my efforts, I kept encountering the following error message: ERROR TypeError: this.deletePriceFactor is not a function at Object.action (price-factor.component.ts:162)

I experimented with arrow functions like this:

action : () =>  { 
         this.deletePriceFactor(params.node.data);
        }

However, this led to yet another error: core.js:1673 ERROR TypeError: Cannot read property 'deletePriceFactor' of undefined

Answer №1

If your HTML structure looks like this:

<ag-grid-angular
      [getContextMenuItems]="getContextMenuItems"
      .
      .
      .
    ></ag-grid-angular>

Then the getContextMenuItems function should be written as follows:

getContextMenuItems = (params) => {
}

By doing this, the this keyword will reference your component.

Next, you can call your method in the following way:

action: () => this.deletePriceFactor(params.node.data)

Answer №2

To incorporate the reference into the grid's context, follow these steps:

this.gridOptions.context = {
    thisComponent : this
};

Subsequently, access thisComponent as shown below:

private getContextMenuItems(params) { 
    console.log(params);
    var result = [
        { // custom item
            name: 'Sample',
            action: function () { params.context.thisComponent.callMe(); },
            icon: '<i class="fa fa-pencil" />'
        }];
    return result;
}

The same approach can be applied to other callbacks like cellRenderer.

For more information, refer to Scoping issues while using context menu

This method has proven effective for me.

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

There is no overload that matches this call in Next.js/Typescript

I encountered a type error stating that no overload matches this call. Overload 1 of 3, '(props: PolymorphicComponentProps<"web", FastOmit<Omit<AnchorHTMLAttributes, keyof InternalLinkProps> & InternalLinkProps & { ...; ...

The Typescript SyntaxError occurs when attempting to use an import statement outside of a module, typically within a separate file that contains

I am currently developing a Minecraft bot using the mineflayer library from GitHub. To make my code more organized and reusable, I decided to switch to TypeScript and ensure readability in my project structure (see image here: https://i.stack.imgur.com/znX ...

The module 'AppModule' has encountered an unexpected declaration of 'AnyComponent'

Hi there, I'm currently working with Angular2 and am facing an issue when trying to use two classes in the same Typescript file. During compile time, no errors are shown. However, when attempting to run the page, the console.log displays the followin ...

Creating a type definition for a TypeScript InfiniteScroll component in React

I am currently in the process of developing an InfiniteScroll component to be used like this: import { getData } from 'api'; import { InfiniteScroll } from 'components'; export const App = () => ( <InfiniteScroll fetcher={page ...

Concatenate all sub-items within a JSON object

I have 2 Objects like this : [ { _id: ObjectId("62990f96345ef9001d9f2dfe"), deletedAt: null, expiredAt: ISODate("2022-06-05T19:29:26.746Z"), dataBarang: [ { vendor: ObjectId("6215dd91139c99003fe4c7cd ...

The information is not displayed on the Angular multi-select dropdown

Having an issue where the data is stored in an object and when I try to map it to an ng multiselect dropdown, the values are not displaying in the dropdown. This is happening with Angular 7. <div class="form group mltslt" *ngIf="individual==true"> ...

The request for PUT, POST, and DELETE methods has been terminated

Issue Encountering the following problem: https://i.sstatic.net/aUF0m.png Scenario Pinning down the exact reason and providing detailed information is proving to be a challenge. In essence, the setup involves an Angular + Express.js application, MySQL f ...

Unveiling the magic: Dynamically displaying or concealing fields in Angular Reactive forms based on conditions

In my current scenario, there are three types of users: 1. Admin with 3 fields: email, firstname, lastname. 2. Employee with 4 fields: email, firstname, lastname, contact. 3. Front Office with 5 fields: email, firstname, lastname, airline details, vendo ...

Angular 2 testing encounters an issue with ViewUtils when setBaseTestProviders() is used

Encountering an issue when utilizing the 'setBaseTestProviders(..)' method, a console error arises. Our current version of Angular is 2.0.0-rc.1. The test located at (test/areas-list.component.spec.ts) looks like this: import {setBaseTestProv ...

Filtering without specifying a data type and (with any luck) converting

Upon defining the function below: const filterAndCast = <T, U>( items: T[], predicate: Predicate<T>, cast: (x: T) => U, ) => items .reduce( (p, c) => [ ...p, ...(predicate(c) ? [cast(c)] ...

What is the best method for accessing all the projected elements within a Component?

What is the best approach for accessing all projected elements within a Component? Consider an example where AppComponent projects various links and images into TestComponent: @Component({ selector: 'test', template: '<ng-content> ...

angular2-jwt: AuthHttp triggers a 'Expected 0 type arguments, but received 1' error

When utilizing AuthHttp from the angular2-jwt library in the code snippet below, an error is encountered: "Expected 0 type arguments, but got 1." public fetchData(): Observable<User[]>{ const apiUrl = environment.apiUrl + "users"; return this.auth ...

Error: The TypeScript aliases defined in tsconfig.json cannot be located

Having trouble finding the user-defined paths in tsconfig.json – TypeScript keeps throwing errors... Tried resetting the entire project, using default ts configs, double-checked all settings, and made sure everything was up-to-date. But still no luck. H ...

Executing multiple service calls in Angular2

Is there a way to optimize the number of requests made to a service? I need to retrieve data from my database in batches of 1000 entries each time. Currently, I have a loop set up like this: while (!done) { ... } This approach results in unnecessary re ...

Angular 4: Error when trying to activate route with empty route parameter: 'Attempting to provide 'null' instead of a stream...'

When accessing /my/route/8000, everything functions as expected. However, attempting to access /my/route without any route parameters results in an error: An error occurred: 'null' was provided instead of a stream. Ensure you provide an Observa ...

The information being fetched from the API via the service to the component appears to be in object form and may require conversion to an array format for compatibility

Whenever I receive data, one set works perfectly while another set does not Data that is functioning properly looks like this data: Array(16) On the other hand, the problematic data appears as follows data: Menu1Items: Array(5) > 0 { .... } etc ...

Angular: Where does the problem lie - with the application or the deployment?

Currently, I am in the process of creating my own personal website using Angular(v4+). I understand that Angular may seem like a complex framework for a simple website, but I am using it because I am eager to improve my skills with it. During development, ...

Changing String Dates to JavaScript Dates

Currently, I am dealing with Fullcalendar's events that return dates in String format, such as 'Wed Oct 23 2019 00:00:00 GMT+0530 (India Standard Time)'. My goal is to convert this string into a JavaScript date while maintaining the exact sa ...

Retrieve all work items from Azure DevOps by utilizing the GET API endpoint

I am currently working with TypeScript and using a GET API to display all work items in the UI. At the moment, there are 4 work items visible on the UI. Along with this, I am also utilizing a POST API to add new work items so that they can be reflected bot ...

What is the best way to utilize lodash in order to inspect every element within a collection, excluding those that do not fulfill my specified condition

let allChecked = _.every(this.collection, this.checked); I'm working on tweaking an existing code snippet that currently evaluates to true if every item in the collection has the checked property set to true. My goal is to adjust it so that it only c ...