Having trouble invoking an Angular 6 Service using an HTML EventListener

Within my angular ag-grid setup, I've implemented a cellRenderer and cellRendererParams. The cellRenderer calls a method to generate a button in each cell of the ag-grid.

constructor(private notificationService: NotificationService) { }

ngOnInit() {
    this.columnDefs = [{
            headerName: "Action",
            field: "notificationId",
            width: 180,
            cellRenderer: this.notificationCellRendererFunc,
            cellRendererParams: {
              notificationId: 'notificationId'
            }
          }];
}

The notificationCellRendererFunc is as follows:

notificationCellRendererFunc(params) {
    var self = this;
    var eSpan = document.createElement('button');
    console.log(params.value); // logs notificationId
    eSpan.innerHTML = 'Resend';
    eSpan.id = params.value;
    eSpan.addEventListener('click', function (eSpan) {
      alert(eSpan.toElement.id);
      var notificationFilter: any = {};
      notificationFilter.notificationId = eSpan.toElement.id;
      self.notificationService.ResendNotification(notificationFilter)
        .subscribe(
          (data: any) => {
            console.log('in save')
          },
          err => { console.log(err) }, // error
      );

    });
    return eSpan;
  }

In the above method, an eventListener is created for each button, allowing the retrieval of the selected row's notificationId to be sent to the API for processing.

However, I encountered an issue with the 'this' keyword not functioning inside the eventListener, even after assigning 'self' to it externally. The error message displayed is: ERROR TypeError: Cannot read property 'notificationService' of undefined at HTMLButtonElement..

My goal is to have a button in every row of the ag-grid, triggering the notification resend function upon clicking.

Answer №1

If you're not utilizing arrow functions, one way to do it is:

espan.addEventListener('click', () => {
 // Insert your code here
});

For more information, you can read this informative article:

Answer №2

To ensure you have access to your service, you must bind your object to the function. If you need further guidance, check out this resource: How to handle event listeners for dynamic elements in Angular?

An example of the code you should implement is shown below:

 element.addEventListener('mouseover', function (element) {
          alert(element.currentTarget.id);
          var filter: any = {};
          filter.elementId = element.currentTarget.id;
          this.service.UpdateElement(filter)
            .subscribe(
              (response: any) => {
                console.log('update successful')
              },
              err => { console.log(err) }, // handle error
          );

        }.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

Angular service is continuously throwing the error message "NullInjectorError: No provider for anotherService"

I recently built a basic Angular service and encountered an issue. @Injectable() export class someHandler { constructor( public anotherService: anotherService, ) {} ... The problem arises when I try to use this service in a component, as ...

Trouble with Angular 2 template variable not being updated within ngSwitch

My code involves a variable called threadCount that is set based on user input and displayed on the same page. Everything works smoothly with regular interpolation <p>Threads: {{threadCount}}</p> But I also want to append it to specific thre ...

Arranging Alphanumeric Characters in Typescript

Given input -> const s = ['2.1.1.a', '2.1.a', '2.1.1.d', 'A2.2', 'A2.1', 2.1.1.c', '2.1.b', '2.1.1.b'] Expected output after sorting -> const s = ['2.1.a', '2. ...

Full width divider for Ionic 2 lists

I am currently facing an issue with my Ionic 2 app where the divider is only full width on the last element in the list. I would like all elements to have a full width border, but I couldn't find any information about this in the documentation. Any he ...

Eliminating the most recent entry from the dropdown menu

Currently, I am exploring angular drag and drop functionality in my project. Here is the code snippet that I am using: Link to Code In the implementation, whenever an item is dropped, it automatically goes to the end of the "done" list. What I am looking ...

"Utilize ngclass to set CSS classes based on enum string values

Is there a way to directly call an element in Angular when using an enum to organize component styles? Instead of writing multiple ng class expressions or dynamically passing them to the element call. button-types.ts export enum ButtonTypes { Primary ...

TypeScript's function types

Regarding my previous inquiry: Transforming PropTypes compatibility into TypeScript If I have this specific function to pass: const displayIcon = () => <span class='material-icons'>account_circle</span> And, the displayIcon func ...

Enhance your bootstrap accordion by incorporating stylish up and down arrows using the <accordion> element

I am currently developing a sophisticated web application using Angular and TypeScript, and I have decided to incorporate accordions in some sections. The setup for these accordions involves TypeScript/Bootstrap as shown below: <accordion> <acco ...

Including files in node package without specifying the name of the dist directory

In my library directory structure for seamless import by node js projects, it looks like this: my-lib/ ├─ dist/ │ ├─ index.js │ ├─ foo.js ├─ src/ │ ├─ index.ts │ ├─ foo.ts ├─ package.json Take a look at my package.j ...

Firebase: The getIdToken() function returned an error indicating that the promise type is not compatible with a string parameter

When attempting to send the Authorized IdToken as a string in HTTP requests to Firebase, I encountered this error message: Argument of type 'Promise' is not assignable to parameter of type 'string' Firebase Auth: getIdToken() fetc ...

Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the atta ...

The request/response is missing property "x" in type "y" but it is required in type "z" during fetch operation

I have configured an interface specifically for utilization with an asynchronous function: interface PostScriptTagResponse { script_tag : { readonly id : number , src : string , event : string , readonly created_at : string , readonl ...

Experience feelings of bewilderment when encountering TypeScript and Angular as you navigate through the

Exploring Angular and TypeScript for an Ionic project, I am working on a simple functionality. A button click changes the text displayed, followed by another change after a short delay. I'm facing confusion around why "this.text" does not work as exp ...

The function does not throw a compiler error when a parameter is missing

Currently utilizing TSC Version 2.4.2 Please take note of the following interface: interface CallbackWithNameParameter { cb: (name: string) => void } This code snippet: const aCallback: CallbackWithNameParameter = { cb: () => {} }; Manages t ...

Angular-cli working in conjunction with an express project

I am currently working on a project that involves Express, MongoDB, and the REST API. I now want to integrate Angular into the project using angular-cli. However, I have several questions about the process. Here is the current structure of my project: htt ...

Guide on transforming JSON data into a collection of custom objects using TypeScript

When working with raw data in TypeScript (originally a JSON file and imported using import * as raw_data from './json_file.json'): let raw_data: object = {"a": {"name": "Name a", "desc": "Description a ...

Passing a value from an HTML template to a method within an Angular 4 component

Encountering an issue with Angular 4. HTML template markup includes a button: <td><a class="btn btn-danger" (click)="delete()"><i class="fa fa-trash"></i></a></td> Data is assigned to each td from a *ngFor, like {{ da ...

A React component featuring a nested map function should always include a "unique key" prop for each element

I am trying to figure out how to assign a proper Key Value in this component: {var.map((building, index) => { const handles = building.buildingVertices.map((point) => { return ( <DrawingHandle key={`${i ...

Display a unique element depending on the path of the Dynamic Angular Routing

Here are the routes I am working with: /dashboard /dashboard/view-all /dashboard/edit/:id One specific issue I've encountered is related to showing/hiding the EditComponent based on the dynamic router. Typically, I can show/hide Angular components ...

Incorporating the id attribute into the FormControl element or its parent in Angular 7

I'm attempting to assign an id attribute to the first invalid form control upon form submission using Angular reactive forms. Here is my current component code: onSubmit() { if (this.form.invalid) { this.scrollToError(); } else { ...