Utilizing event bubbling in Angular: a comprehensive guide

When using Jquery, a single event listener was added to the <ul> element in order to listen for events on the current li by utilizing event bubbling.

<ul>
 <li>a</li>
 <li>b</li>
 <li>c</li>
 <li>d</li>
</ul>

Now, looking to achieve the same functionality in angular:

1) I am attempting the following approach:

I can only retrieve the selected list element using $event.target, but I am unable to access the data bound to the list items.

<ul (click)="onListClick($event)">
    <li *ngFor="let data of [1, 2, 3, 4]"></li>
</ul>

2) Alternatively, I found that I can access the data bound to the list item within the click listener when applying it directly to the li elements:

<ul>
    <li (click)="onListClick(data)" *ngFor="let data of [1, 2, 3, 4]"></li>
</ul>

Note: The main objective is to reduce the number of event listeners, hence binding the event to the <ul> tag instead of individual <li> elements. However, we still need to find a way to pass the data from the clicked <li> element to the <ul> click listener function.

Answer №1

One way to assign values to list items is by using property binding syntax

<ul (click)="handleListClick($event)">
    <li *ngFor="let item of [5, 6, 7, 8]" [value]="item">{{item}}</li>
</ul>

handleListClick(event) {
   console.log(event.target.value);
}

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

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

Tips for activating scroll feature for certain section of an HTML page

For the styling of my page, I'm utilizing Scss and am facing an issue related to setting up scrolling for specific sections of an HTML page. You can check out the image reference here. During a scroll event, I want to ensure that the Categories (left ...

Switching out a traditional class component with a functional component within a hook to deduce properties from T

One challenge is to subtract props from T within the withHookFn function using a function instead of a class as successfully done in the withHook function. The code contains comments explaining this issue. Dive into the code for more insights. import Reac ...

Tips for successfully implementing a redirect in getStaticProps without encountering any TypeScript errors

Issue While using Next.js with TypeScript, an error occurs when attempting to return a redirect in case the data is missing. Solution Attempted import { GetStaticProps } from "next"; import fs from "fs/promises"; import path from " ...

The promise chain from the ngbModal.open function is being bypassed

I'm currently working on implementing data editing within a component. My task involves checking if any of the data fields have been altered, and if so, prompting a confirmation pop-up to appear. If the user confirms the change, the data will then be ...

Retrieve all the characteristics accessible of a particular course

I am facing a situation where I have the following class structure: class A { id: number propertyA: string constructor(id: number) { this.id = id } } let a = new A(3) console.log(SomeFunction(a)) // expected output = ['id', ' ...

Tips on adjusting the Leaflet Map's zoom level to display all markers in React Leaflet

I am currently working on a project with React Leaflet map that requires changing the center and zoom based on a set of markers. The goal is to adjust the zoom level so that all the markers are visible on the map. To achieve this change in view, I am util ...

Validating Credit Card Numbers with Spaces

Currently, I am in the process of creating a credit card form that requires validation using checkValidity to match the specific card pattern that is dynamically added to the input field. For example, if a user enters a Mastercard number such as 545454545 ...

What is the best way to incorporate Typescript React Components across various projects?

I'm venturing into developing an npm package that involves several react components implemented with typescript. As a newcomer to react and npm, I apologize if my query seems basic. Despite researching online, there isn't much information on this ...

Error Arises When Making Selection in PrimeNG's P-ListBox Component

Whenever I choose an item from my listbox module, I encounter an error where the value is being returned as an object instead of an array in my listbox.js file from p-listbox by PrimeNG. HTML: <p-listbox formControlName="programType" [options]="phoneT ...

Exploring the Method of Utilizing JSON Attribute in typeScript

How to access JSON attributes in TypeScript while working on an Angular Project? I'm currently in the process of building an Angular project and I need to know how to access JSON attributes within TypeScript. test:string; response:any; w ...

Is it possible to generate a new array by combining the keys of one array object with the values of another array object?

I have a situation with two arrays set up like this arr1 = [ { 'name':'Victoria Cantrell', 'position':'Integer Corporation', 'office':'Croatia', 'ext' ...

Discovering Typescript: Inferring the type of a union containing specific strings

I am working with a specific type called IPermissionAction which includes options like 'update', 'delete', 'create', and 'read'. type IPermissionAction = 'update' | 'delete' | 'create' | ...

What is the maximum number of users that my Laravel app can accommodate when integrated with Pusher?

My app currently has between 300 and 900 subscribers, and I am looking to add real-time product information using pusher.com. While the implementation was straightforward, I found the pricing confusing. The startup plan costs $49 per month and allows for ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...

Tips for transforming promise function into rxjs Observables in Angular 10

As a beginner in typescript and angular, I am trying to understand observables. My query is related to a method that fetches the favicon of a given URL. How can I modify this method to use observables instead of promises? getFavIcon(url: string): Observ ...

Issue with PrimeNg dropdown in a modifiable data table where the chosen value is not retained

Here is the code snippet for the column in the data table: <p-column field="organization.description" header="Partner" [editable]="dtCostShare" [style]="{'width':'30%'}"> ...

What is the method to incorporate type hints for my unique global Vue directives?

When I import or create a directive in an SFC file, I can receive TypeScript hints like this: import vFocus from 'my-custom-component-library'; View demo with ts hints However, if I globally register it in main.ts, the type hints are not availa ...

Utilizing SVG Images on Buttons within Material Design (MD-Icon)

I have experimented with different methods, but none seem to be effective: <button md-icon-button color="primary"> <md-icon md-svg-src="./assets/img/sprites.svg">menu</md-icon> </button> and also tried this: <md-icon svgSrc= ...

Utilizing MongoDB query for geoLocation with maxDistance parameter

Customer location: customerCoordinates: [83,24] stores: { id:1, location: {coordinates:[85,44]...} maxRadiusDelivery: 2000 //meters }, { id:2, location: {coordinates:[82,34]...} maxRadiusDelivery: 100 //meters } Query: db.wh.find({ 'locati ...