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

The Angular ngFor directive is failing to loop through the provided

This is the format I created <div *ngIf="attachments"> <div> {{ 'attachments' | translate }} </div> {{ attachments.data[0].title }} <!-- this line works fine --> <div *ngFor="let item of attachm ...

Utilize the identical function within the reducer for numerous mat-slide-toggle and checkboxes in component.html

I'm currently diving into the world of Angular and ngrx while tackling a project focused on enabling users to create forms. In this project, users can add various form elements (such as labels, text fields, dropdown menus, checkboxes, etc.) from a sid ...

typescript is reporting that the variable has not been defined

interface User { id: number; name?: string; nickname?: string; } interface Info { id: number; city?: string; } type SuperUser = User & Info; let su: SuperUser; su.id = 1; console.log(su); I experimented with intersection types ...

Google Chrome does not support inlined sources when it comes to source maps

Greetings to all who venture across the vast expanse of the internet! I am currently delving into the realm of typescript-code and transcending it into javascript. With the utilization of both --inlineSourceMap and --inlineSources flags, I have observed t ...

Utilizing Angular resolver to inject the router functionality

In my Angular (v13) application, I have defined a resolver to interact with a Wordpress backend. The purpose of this resolver is to determine the post type and ID from Wordpress when a user accesses a URL, and then route accordingly (to a post list, single ...

Creating conditional statements in Angular 2 templates - the power of if, elseif

Can the if elseif else structure be used in an Angular 2 template? Here is an example of using if else: [text]="company ? company.name : 'Select a company'" I am looking to incorporate elseif into this. ...

Circular dependency in Typescript/Javascript: Attempting to extend a class with an undefined value will result in an error,

Query Greetings, encountering an issue with the code snippet below: TypeError: Super constructor null of SecondChild is not a constructor at new SecondChild (<anonymous>:8:19) at <anonymous>:49:13 at dn (<anonymous>:16:5449) ...

Ensuring type compatibility in a declarative manner: What are the methods?

My goal is to establish a compile-time constraint that ensures a variable of type T2 can be assigned to a variable of type T1. If I have a value (t2) of type T2, I can simply do the following: const t1: T1 = t2; Is there an alternative method to achiev ...

Ways to fake an interface using Jest without needing to instantiate it

While Kotlin supports this, I haven't been able to find a way to achieve the same in Jest. My problem arises from having intricate interfaces and arrays of these interfaces where specifying all attribute values is not ideal. Here's an example of ...

Is it possible for me to use an array as an argument for the rest parameter?

One of the functions in my codebase accepts a rest parameter. function getByIds(...ids: string){ ... } I have tested calling getByIds('andrew') and getByIds('andrew','jackson'), which successfully converts the strings into a ...

Typescript: Retrieve an interface containing properties that are found in interface A, but not in interface B

I am currently developing a mapper that will facilitate the translation between a serialized entity state and a form state. In the context of two given interfaces A and B, I am exploring ways to derive a third interface C that includes properties present ...

Issue with the Material UI theme module enhancement feature not functioning as expected

I've been researching the MUI documentation, blogs, and various posts on Stackoverflow, but despite my efforts, I can't seem to get my vscode intellisense/typescript to recognize the changes I've made. These are fairly straightforward modif ...

What are the steps for incorporating the AAD B2C functionality into an Angular2 application with TypeScript?

I recently built a web application using Angular2 and TypeScript, but now one of my clients wants to integrate Azure B2C for customer login instead of OAuth. I followed a simple example on how to implement Azure B2C in a .NET Web app through the link provi ...

Choosing Vue select options depending on a condition

I am working on a dropdown template with Vue.js and have encountered some challenges. Here is the basic structure of my dropdown: <select v-model="selectedClient" class="stat-select text-u-c"> <option disabled value="">Please select a Client ...

Exploring ways to display all filtered chips in Angular

As a new developer working on an existing codebase, my current task involves displaying all the chips inside a card when a specific chip is selected from the Chip List. However, I'm struggling to modify the code to achieve this functionality. Any help ...

Angular with RxJS: Observable with synchronous data flow

One of the services I have includes a method called foo. In this method, I am subscribing to an observable (http-client). foo () : boolean { let ret : false; this.http.get ("/blabla").subscribe ( (resp) => { ret = true; } return ret; ) ...

Incorporating yarn into your Vue3 project with Typescript

I'm attempting to implement a solution from https://yarnpkg.com/package/vue-disable-autocomplete that disables autocomplete in my Vue3 project. After running yarn add vue-disable-autocomplete, I included the following code: import DisableAutocomplete ...

How can I make the snackbar open multiple times in a row?

Check out this codesandbox I created to show an issue. When you click the button, a MUI snackbar opens. However, if you close it and try to reopen it, nothing happens. Do you think the problem is related to how I'm using hooks? Explore the sandbox h ...

Which offers a more efficient approach: implementing functionalities within subscribe or in a custom operator with RxJS?

Within my angular application, I frequently utilize a pattern like this: this._store .root .pipe( ..., mergeMap(() => this._httpClient.get<IEvent[]>(`${this.ROUTE}/user/${id}`)) ) .subscribe((events: IEvent[]) => ...

Prevent clicking on cells in the ng-zoro nz-calendar

Hello, I am using a nz-calendar and I need help disabling clicks on cells. <nz-calendar [(ngModel)]="date" [(nzMode)]="mode" > <div *nzDateCell="let date" class="date-cell"> <ng ...