Using Angular to bind a click event to an element after it has been compiled

I am currently developing an application for students using Angular 5. In this application, users can access and view various documents. When a user enters a document, a set of tools, including a marker tool, are displayed. This marker tool allows users to highlight text within the document. These markers are saved on the server with a unique ID assigned to each marker in the document. The document structure is as follows:

[{
        "chapterId": "254125",
        "title": "Some random title",
        "blocks": [{
                "blockId": "12654654",
                "blockContent": {
                    "text": "Lorem ipsum dolor sit amet..."
                }
            },
            {
                "blockId": "12654654",
                "blockContent": {
                    "text": "Lorem ipsum dolor sit amet..."
                }
            },
            {
                "blockId": "12654654",
                "blockContent": {
                    "text": "Lorem ipsum dolor sit amet..."
                }
            }
        ]
    },
    {
        "chapterId": "254125",
        "title": "Another random title",
        "blocks": [{
                "blockId": "12654654",
                "blockContent": {
                    "text": "Lorem ipsum dolor sit amet..."
                }
            },
            {
                "blockId": "12654654",
                "blockContent": {
                    "text": "Lorem ipsum dolor sit amet..."
                }
            },
            {
                "blockId": "12654654",
                "blockContent": {
                    "text": "Lorem ipsum dolor sit amet..."
                }
            }
        ]
    }
]

Each block represents a paragraph in a chapter. By looping through the chapters and blocks within each chapter, I create the actual document (Document example). When retrieving markers from the server, I receive an object like this:

{
  "id": 20,
  "start": 125,
  "end": 258,
  "color": "red",
  "chapterId": 12631561,
  "blockId": 121651
}

Using this information, I search for the appropriate chapter and block to place the marker at the correct position within the text block:

public placeMarkerOnBlock(chapter, marker): any {
    let tempText: string = '';

    /* Here we loop the blocks to find the right one to place the marker. */
    chapter.blocks.some((block) => {
      if (marker.blockId === block.blockId) {
        const blockText = block.blockElement.text;
        // Other logic for placing the marker within the text
      }
    });
    return chapter;
  }

After setting up the markers, I need to attach a click event handler to each marker so that when users click on a marker within the text, a small bubble appears with an option to remove that specific marker. However, I have been facing challenges with adding the (click)="" event dynamically. Is there an alternative approach to achieve this functionality more effectively?

Answer №1

It seems like the issue you're encountering is due to trying to attach an event to dynamically generated and dynamic nature HTML elements. If you are using jQuery, you can attach a click event to dynamic HTML like this:

 $(document).on("click", "a.remove" , function() {
        // add your logic here
    }); 

Here, "a.remove" refers to: a: an anchor tag that is dynamically generated, remove: a regular class on the anchor tag.

If you prefer not to use jQuery and would like to handle everything in Angular, you can load your HTML in the life cycle hook ngOnInit(). Once the HTML has fully loaded, you can then create a click event on dynamically generated HTML using ngAfterViewInit().

 ngAfterViewInit(): void {

 // write logic to add click event to generated html
}

 ngOnInit() {
    //load your data here
}

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

Error occurs when attempting to call Angular from NodeJS

I am trying to integrate Angular with Node.js, but I'm encountering an error while accessing it in the browser. Angular works fine when I run "node server." Error: runtime.js:1 Uncaught SyntaxError: Unexpected token < polyfills.js:1 Uncaught Synt ...

What is the best way to fully reload an Angular component when the route is changed?

I'm looking for a way to reload or refresh a sidebar component when the route changes. Below is the code I currently have: constructor( private auth: AuthService, private router: Router, private changeDetector: ChangeDetectorRef ) { ...

Exploring the power of makeStyles in Material UI when combined with TypeScript

I am currently in the process of converting a JavaScript template to Typescript. Here is an example of my accordionStyle.ts file: import { primaryColor, grayColor } from "../../material-dashboard-pro-react"; const accordionStyle = (theme?:an ...

The function validation_1.validateName in Ionic/Angular is not recognized as a valid function, causing an error that prevents

My development environment includes Ionic Angular. After upgrading from Angular 9 to Angular 14 and Ionic 4 to Ionic 5, I encountered an issue where I can no longer generate pages or components using the command: ionic g page [PATH] The process now trigge ...

Simple methods for ensuring a minimum time interval between observable emittance

My RxJS observable is set to emit values at random intervals ranging from 0 to 1000ms. Is there a way to confirm that there is always a minimum gap of 200ms between each emission without skipping or dropping any values, while ensuring they are emitted in ...

Struggling to retrieve the 'this' object using a dynamic string

Within my Nuxt + TS App, I have a method that attempts to call a function: nextPage(paginationName: string): void { this[`${paginationName}Data`].pagination .nextPage() .then((newPage: number) => { this.getData(pagination ...

Adjust the setting for the useHash parameter within the RouterModule during execution

I am faced with a situation where I need to dynamically load my router module option useHash in my Angular application, sometimes with true and other times with false. This decision depends on the server state data that is available in the global window ob ...

Angular 2 Mixup: Using Leaflet and Google Maps with Incorrect Tile Order

I am encountering an issue while working on Leaflet and Google within Angular 2. The problem lies in the Tilemill tiles not rendering properly as they are displaying in a strange order. Here is a screenshot of the current state: https://i.stack.imgur.com/ ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

Utilizing Filters (Pipes) in Angular 2 Components without Involving the DOM Filters

When working in Angular 1, we have the ability to use filters in both the DOM and Typescript/Javascript. However, when using Angular 2, we utilize pipes for similar functionality, but these pipes can only be accessed within the DOM. Is there a different ap ...

I want to create a feature in Angular where a specific header becomes sticky based on the user's scroll position on the

When working with Angular, I am faced with the challenge of making a panel header sticky based on the user's scroll position on the page. I have identified two potential solutions for achieving this functionality. One involves using pure CSS with pos ...

The powerful combination of Visual Studio 2015, TypeScript, Cordova, Angular 2, and System

I am encountering an issue with the loading of external modules using systemJS. I have created a small sample project for VS2015. Feel free to check out the code here: https://github.com/dbiele/TypeScript-Cordova-SystemJS After building the project and at ...

A Step-by-Step Guide on Modifying the Default Button in Angular2CSV

I am currently utilizing Angular 4 along with the Angular2CSV plugin to transfer data from an Angular page to Microsoft Excel. The process has been successful thus far. However, I am interested in changing the name of the button but am unsure of how to d ...

What is the best way to add a clickable link/button in Angular 8 that opens a webpage in a new tab?

I'm looking to create a website that opens in a new tab when a link or button is clicked. I'm unsure how to achieve this in Angular 8. ...

Discovering the JavaScript source file for a package using WebStorm and TypeScript

In my TypeScript project, there is a usage of Express with the following method: response.send('Hello'); I am interested in exploring the implementation of the send() method. However, when I try to navigate to the source code by ctrl+clicking o ...

ASP.NET Core responds with a 404 error when an Angular request is made

I am currently working with ASP.NET Core in combination with Angular 2+. In my project, I have a Controller setup like this: public class ValuesController : Controller { [HttpGet] [Route("api/values/get")] [ResponseCache(NoStore = true, Lo ...

How can one click the button within the expanded dropdown while hovering over the navigation item in Angular and Bootstrap?

Issue Description: Upon hovering over a navigation item, the dropdown container is displayed but it's not clickable. Desired Behavior: Hovering over a navigation item should display the dropdown container and allow clicking on its contents. Furthermo ...

Having difficulty importing SVG files in TypeScript

When working with TypeScript (*.tsx) files, I encountered an issue where I couldn't import an SVG file using the following statement: import logo from './logo.svg'; The transpiler gave me this error message: [ts] cannot find module '. ...

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...

Transferring information between screens in Ionic Framework 2

I'm a beginner in the world of Ionic and I've encountered an issue with my code. In my restaurant.html page, I have a list of restaurants that, when clicked, should display the full details on another page. However, it seems that the details for ...