Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element.

<ul>
 <li id="1" class="selectModal">First</li>
 <li id="2" class="selectModal">Second</li>
 <li id="3" class="selectModal">Third</li>
</ul>

Answer №1

Exploring various methods to achieve this goal. A simple solution can be implemented as follows:

<ul (click)="handleClick($event.target)">
 <li id="1" class="toggleModal">Primary</li>
 <li id="2" class="toggleModal">Secondary</li>
 <li id="3" class="toggleModal">Tertiary</li>
</ul>

handleClick(eventTarget: HTMLElement) {
    console.log(eventTarget.id, eventTarget.className);
}

Answer №2

Absolutely, the approach you take depends on your strategy. One way to achieve this is through jQuery or by utilizing DOM accessors. In my experience working with a team, we prefer using JQuery, but we avoid searching the entire DOM to locate elements. Instead, we utilize a class known as ElementRef:

import { ElementRef } from '@angular/core';
...
constructor(private elementRef : ElementRef) {
}

ngAfterViewInit() {
    jQuery(this.elementRef.nativeElement).find('selectModal').on('click', () => {
    //perform actions here
    });
}

The ElementRef class serves as a reference to the component within the DOM, allowing us to narrow down our search specifically to this component.

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

What is preventing Node.js from executing my JavaScript code in the terminal?

I need help understanding why my JavaScript code isn't working properly. Can someone explain the Uncaught SyntaxError: Unexpected Identifier error message? ...

Next-auth is in need of a username for the credentials provider

I am currently trying to learn how to implement next-auth in Next.js 13. I have set up a credentials login system with username and password. When I make an API request, I expect to receive a status code of 200 if the credentials are correct. The logic f ...

Retrieve isolated scope of directive from transcluded content

I am not certain if it is possible, but I am essentially looking for a reverse version of the '&' isolate scope in AngularJS. You can check out this Plunkr to see an example. In essence, I have created a custom directive that provides some r ...

Transitioning React components organized in groups to TypeScript

As I transition my react project to incorporate typescript, one challenge I encountered was adjusting the file structure. In its simplified form, here is how the original js project's file structure looked like: src components index.js inputs butt ...

What is the reason Node.js only prints one item at a time?

Currently, I am using node.js to extract items from a text file. Right now, the code prints out the items in the terminal, but I want it to be able to accept multiple parameters and print each of them individually instead of just the last one. // Checki ...

Searching the Google Place API to generate a response for dialogflow

I am currently facing an issue while trying to utilize the Google Place API for retrieving details to display a map (by fetching coordinates) and location information (address) as a response from my chatbot. I have created this code snippet, but encounteri ...

Updating the content of a list item on the fly using React

After spending all day on this, I am feeling a bit frazzled. Trying to achieve what would take 20 seconds in JQuery has proven to be quite the challenge in React ¯\_(ツ)_/¯ In my application, tags are ranked by importance from 1 to 9. Simple enoug ...

Having trouble with Angular UI Select functionality?

I have integrated the angular ui select library from https://github.com/angular-ui/ui-select into my project. Instead of using the traditional select element, I am now utilizing the ui-select directive. This is a snippet of my code: <select class=" ...

Dynamically taking input in Vue JS while using v-for loop

Hey there! I'm trying to get input in this specific manner: itemPrices: [{regionId: "A", price: "200"},{regionId: "B", price: "100"}] Whenever the user clicks on the add button, new input fields should be added ...

I am attempting to access an Angular variable using JavaScript, but unfortunately, I am encountering some issues

I'm currently implementing the following code: window.onload=function(){ var dom_el2 = document.querySelector('[ng-controller="myCtrl"]'); var ng_el2 = angular.element(dom_el2); var ng_el_scope2 = ng_el2.scope(); console.log ...

What is the process for transmitting data in JSON format generated by Python to JavaScript?

Utilizing Python libraries cherrypy and Jinja, my web pages are being served by two Python files: Main.py (responsible for handling web pages) and search.py (containing server-side functions). I have implemented a dynamic dropdown list using JavaScript w ...

Using Express and Node.js to implement the Google Maps API

Currently working on creating a simple web application using the Google Maps API with express/node. At the moment, I have three main files that make up my project: server.js const express = require('express'); const bodyParser = require(' ...

What could be the root cause behind the error encountered while trying to authenticate a JWT?

I've been working on integrating a Google OAuth login feature. Once the user successfully logs in with their Google account, a JWT token is sent to this endpoint on my Express server, where it is then decoded using jsonwebtoken: app.post('/login/ ...

Inheritance of Generic Types in TypeScript

Could someone assist me in understanding what is incorrect with the code snippet provided here? I am still learning Typescript. interface ICalcValue { readonly IsNumber: boolean; readonly IsString: boolean; } interface ICalcValue<T> ex ...

Fresh ajax requests are not clearing the current data displayed in the JSP table

My ajax function retrieves data from a servlet and displays it in the page successfully. However, each time a new ajax call is made, the form appends the new data to the existing results instead of replacing them. I need to reset the current values stored ...

Error: The property you are trying to set is undefined and cannot

When I attempt to set a property 'error' that is undefined, I receive a TypeError. The problematic line of code looks like this: this.error = error.code; This issue arises in an Angular Reactive Form while making a call to a web service. Below i ...

How to transfer identification from one AngularJS page to another

I need help figuring out how to retrieve an ID from the list.html page and use that same ID to display corresponding details on the list-detail.html page. I am new to using angularjs and struggling with getting the details based on the ID. Below is my code ...

How to iteratively process JSON array using JavaScript?

I am currently attempting to iterate through the JSON array provided below: { "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "<a href="/cdn-cgi/l/email-pro ...

How to use jQuery Animate to create a step-by-step animation with image sprites?

I'm working on creating an image sprite using jQuery and I'm curious if it's feasible to animate it in steps rather than a linear motion. I initially tried using CSS3 animations, but since IE9 is a requirement, the animations didn't wor ...

Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated! Thank you in advance for your time. This is what I've put together, but it's not functioning as expected: app.post( ...