Using Angular service within InnerHTML functions

Within my Angular 10 application, I am utilizing innerHtml to display some content that includes anchor links.

My goal is to trigger a function every time a link is clicked, which will then invoke an Angular service.

In the code snippet below, I am attaching an addEventListener to all the links:

ngAfterViewInit() {
    this.privacy_policy = this.elementRef.nativeElement.querySelectorAll('a.privacy_policy');
    this.privacy_policy.forEach((anchor: HTMLAnchorElement) => {
      anchor.addEventListener('click', this.taggingPrivacyPolicy);
    })
}

taggingPrivacyPolicy() {
    const eventTag: EventTag = {
        z_eventplace: 'terms_and_conditions',
        z_eventtype: 'privacy_policy',
        z_eventvalue: `${this.brand}_policy`
    };
    this.taggingService.tagEvent(`${this.brand}_policy`, eventTag, 'onclick');
    console.log('clicked');
}

However, when a user clicks on the link, I encounter the following error:

ERROR TypeError: Cannot read property 'tagEvent' of undefined

What steps can be taken to resolve this issue?

Answer №1

It seems like the this reference is slipping away from you. Give this a shot:

anchor.addEventListener('click', this.taggingPrivacyPolicy.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

Utilizing a drop-down selection menu and a designated container to store chosen preferences

My form includes a select dropdown that displays available options (populated from a PHP database). Users can choose options from the list, which are then added to a box below to show all selected items. However, I am facing a challenge with the multiple s ...

Patience is key as you await the element to load and smoothly render the data in vue.JS

Is there a way to ensure that the graph is only rendered and filled with data after the data has been returned from the backend? Currently, even though the data is returned, the graph appears blank. Here is my JavaScript code: methods: { refresh( ...

What's the alternative for $rootScope in Angular 2?

I am currently developing a demo application using Angular 2, and I have encountered a problem. I need to utilize a global variable or object across the entire application similar to $rootScope in Angular. Could you please provide me with some suggestions ...

Trouble accessing selected value from drop down list in ASP.NET codebehind following modification of Javascript attribute

Does anyone know why ASP.NET code behind cannot retrieve the selected value? After investigating, I discovered that the issue lies within the JavaScript function; Specifically in the set attribute section: process.options[process.selectedIndex].setAttrib ...

Using Javascript to delete an HTML list

Currently, I am working on a webpage that includes notifications along with options to mark them as read individually or all at once. However, when attempting to use my loop function to mark all notifications as read, I noticed an issue. let markAllAsRead ...

The hover effect becomes disabled once the slider is toggled

My table has a feature where I can change the background color and other elements using a slider. However, I'm facing an issue where the hover effect on the table stops working when I toggle the slider on or off. I attempted to solve this with a funct ...

Is there a way to dynamically set a database path in Express.js depending on the user's login status?

I have a backend service that serves as the primary entry point for my web application, where I want to dynamically allocate a database path based on user login. While I understand that this solution may not be scalable in the long run, I plan to use it fo ...

Transmitting information securely and remotely between two online platforms

I own two websites and another at When a user clicks on something on example1.com, I want it to trigger a popup from example2.com. Then, I need to send some data back to example1.com using GET parameters and be able to detect it using jQuery or JavaScrip ...

utilizing a pair of API requests within a personalized Alexa skill

I posted a question about integrating Alexa with the Steam custom skill API here, but I realize it might be too detailed for some to read through. In essence, my main question is: Can you make two separate API calls within the same block of JS code while ...

Error Alert: Invalid Hook Call detected while using the useSelector hook within a Functional Component

I am encountering an error Error: Invalid hook call. Hooks can only be called inside of the body of a function component. The versions of React and the renderer (such as React DOM) might not match There could be violations of the Rules of Hooks Multiple ...

I encounter difficulties using my static resources in the root route of my Express.js application

Can you guide me on how to implement styles and images from the assets folder in my webpage, specifically for the root route? As an example, I have a styles.css file located at assets/styles.css. In my code, I am using app.use(express.static('assets&a ...

Puzzled by the unexpected error I encountered while using Node.js (require.js)

My script was running smoothly until I encountered a sudden error: undefined:3 <!DOCTYPE html> ^ SyntaxError: Unexpected token < at Object.parse (native) at Request._callback (C:\Users\Tom\Pictures&bso ...

Making a POST request with ajax in Django

I encountered some difficulties while attempting to send a POST request using ajax in Django. I have searched various resources, but have not yet found a solution. Below is the javascript code that I am using, following this guide: $.ajax({ url: &apo ...

The contents of the div disappear when using jQuery to extract it from a string

Update: I finally uncovered the reason behind the empty content of the #output div. The content is fetched from the server, which takes some time; by the time the document loads, the div remains empty. Does anyone have suggestions on how to extract infor ...

Angular Command Line Interface version 12.2.0 displays the message: "No overload matches this call."

I've been working on developing a shopping cart feature for an Angular project. I'm trying to define a product as a Product type, but I keep encountering an error message stating: "(product: Product) => { ..." The error message rea ...

Is there a way to dynamically pass values to a form in React?

Learning React on my own has been challenging, especially when trying to accomplish what I thought would be a simple task. To put it briefly, I have a menu with several items. I aim to select a menu item and have a form open next to it. The form shoul ...

What is the best way to save a Map for future use in different components?

Let's say I define an enum like this: export enum SomeEnum { SomeLongName = 1, AnotherName = 2 } Within my display components, I'm utilizing an enum map to translate the enum values into strings for presentation on the web app: enumMap = new Map ...

There was an issue processing your request as some parameters are either invalid or missing in the express and node

I am facing a challenge in retrieving the access token of the user through LINE oauth2. While I can successfully redirect the user to the callback URL and generate the code in the URL, I encounter an error when trying to implement it in my code. "Invali ...

Personalized Functions Using Material Design Expansion Panel Header Icon

Here's a unique material design accordion with an icon added to the panel header. I want to invoke my function 'myFun()' on click event, but currently, the expansion panel is toggling each time it's clicked (which is not the desired beh ...

Guide to accessing Realm(JavaScript) object in an asynchronous manner and integrating it with various services

I have incorporated the following code into my project to open Realm asynchronously and integrate it with services. RmProfile.js: import Realm from 'realm'; const PrflSchema = { name: 'Profile', primaryKey: 'id', prope ...