What is the reason behind not being able to fetch the element id while using event.target?

When I click on the button, I'm trying to retrieve the element id, but sometimes I don't get it. Here's the code snippet where I encounter this issue using TypeScript!

Take a look at the image below!

          <div *ngFor="let item of l">
              <input type="text" class="form-control">
              <button (click)="getRate($event)"><i class="far fa-star" id='1'></i></button>
              <button (click)="getRate($event)"><i class="far fa-star" id='2'></i></button>
              <button (click)="getRate($event)"><i class="far fa-star" id='3'></i></button>
              <button (click)="getRate($event)"><i class="far fa-star" id='4'></i></button>
              <button (click)="getRate($event)"><i class="far fa-star" id='5'></i></button>
          </div>

A method in Typescript to calculate the rate based on the star's ID.

  getRate(event: Event) {
    this.ratesArray.push((((event.target as Element).id as unknown) as number) * 20);
    console.log((event.target as Element).id);
    console.log((((event.target as Element).id as unknown) as number));
  }

https://i.sstatic.net/Q7rJO.png

Answer №1

This situation can be a little complex. One key point to note is that there is an i tag within the button element. If you click on the i tag, it will provide the id, otherwise it won't work. In HTML, make sure to use the id attribute in the button tag.

<button (click)="getRate($event)" id='1'><i class="far fa-star" ></i></button>

And in the component file:


getRate(event: Event) {
    var target = event.target || event.srcElement || event.currentTarget;
    var id = target.attributes.id;

  }

Answer №2

I successfully resolved the issue by implementing a function that returns null when the button is clicked, as I am retrieving the id.

getRate(event: Event) {
    //this.ratesArray.push((((event.target as Element).id as unknown) as number) * 20);
    if ((event.target as Element).id == null) {
      console.log((event.target as Element).closest("a").id);
    } else {
      console.log((event.target as Element).id);
    }
    console.log((((event.target as Element).id as unknown) as number));
  }
    <a (click)="getRate($event)" id="1"><i class="far fa-star" id="1"></i></a>
    <a (click)="getRate($event)" id="2"><i class="far fa-star" id="2"></i></a>
    <a (click)="getRate($event)" id="3"><i class="far fa-star" id="3"></i></a>
    <a (click)="getRate($event)" id="4"><i class="far fa-star" id="4"></i></a>
    <a (click)="getRate($event)" id="5"><i class="far fa-star" id="5"></i></a>

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

Tips for retaining scroll position in Angular 2

Suppose I am currently on page 1. I scroll halfway through the page and then click a link that takes me to page 2 using the Angular router. When I use the "back" button, I want page 1 to be scrolled halfway down, just like it was before I left the page. H ...

Encountering CORS policy block when attempting to post data using Geoserver API through Angular

I'm currently working on Angular and I need to integrate the Geoserver API to publish spatial database data. Previously, I successfully used PHP Curl with the API and now I want to incorporate it into my Angular app. It's worth mentioning that ...

Experiencing an issue with Jest - Error: unable to access property 'forEach' of null

After watching some tutorials, I decided to create a sample project in Jest for writing tests. In a TypeScript file, I included a basic calculation function like this: Calc.cs export class Calc { public add(num1: number, num2: number): number { ...

Issue with material table not showing data

Problem I've been working on integrating a material design table into my project, but I'm running into an issue where the data isn't showing up. I followed the example provided here but all I see is a single vertical line on the page: https ...

Controlling animation keyframes in Angular 2: a guide

Is there a way to manipulate CSS3/angular 2 animations using variables? Take a look at this modified code snippet from the official angular 2 animation docs: animations: [ trigger('flyInOut', [ state('in', style({position: &apos ...

Is it possible to retrieve a static resource within server-side code in NextJs?

Exploring the static render feature of NextJS to generate a static version of my website has led me to ensure that all necessary data is provided for the initial page render. I have stored several blog posts as .md files in /static and aim to access them ...

The Angular service successfully provides a value, yet it fails to appear on the webpage

Currently, I am starting to dive into Angular from the ground up. One of my recent tasks involved creating a component called 'mylink' along with a corresponding service. In my attempt to retrieve a string value from the service using 'obse ...

Guide to defining custom variables from various locations within Angular Js

In my Angular 6 project, I have noticed that in the home.component.ts file, there is a variable being declared at the beginning: public hasResults = false; Then in the home.component.html file, there is a section for displaying this variable: <span st ...

A guide to effectively utilizing a TypeScript cast in JSX/TSX components

When trying to cast TypeScript in a .tsx file, the compiler automatically interprets it as JSX. For example: (<HtmlInputElement> event.target).value You will receive an error message stating that: JSX element type 'HtmlInputElement' is ...

An entire line of boxes has been checked off

Currently, I am working on adding an additional column with checkboxes to the Mat table example. However, I noticed that when I click on one checkbox in a column, the checkboxes in other columns also get selected. How can I implement this so that only th ...

"Encountering an 'Access-Control-Allow-Origin' error in the VSCode Debug Console, even though the network tab in Chrome DevTools displays a 200OK

In my Angular 7 project, I encountered an issue while using HttpClient. When I click a button, the following code snippet is executed: this.http .get('http://localhost:30123/api/identity/name/' + this.name) .subscribe((answer: Identit ...

Angular4 ChromeDriver Selenium Protractor

I am facing an issue while trying to run 'ng e2e'. The error message I encounter is as follows: WebDriverError: unknown error: cannot find Chrome binary I am using Protractor which is pre-installed with Angular CLI. Despite reinstalling ChromeD ...

Ways to generate an array containing the headings from a list using typescript?

How can I extract the headers of objects in an array in TypeScript? let data = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}]; let headers = Ob ...

I am trying to figure out how to dynamically set the deployUrl during runtime in Angular

When working with Angular, the definition of "webpack_public_path" or "webpack_require.p" for a project can be done in multiple ways: By setting the deployUrl in the .angular-cli.json file By adding --deployUrl "some/path" to the "ng build" command line ...

The PhpStorm code completion feature is not functioning properly when working with TypeScript code that is distributed through NPM

I am facing an issue with two NPM modules, which we will refer to as A and B. Both modules are written in TypeScript and compile into CommonJS Node-like modules. Module B has a dependency on module A, so I have installed it using the command npm install ...

Issue with IE11: Main.js unable to load app.module.js as ./app.module

My angular2 project is currently functioning smoothly in the latest versions of Chrome and Firefox. I am using gulp for my build automation process and systemjs for module loading. However, when I try to access the application in IE11, it fails to load a ...

Error encountered during conversion to Typescript for select event and default value

When trying to set the defaultValue in a Select component, TSlint throws an error - Type 'string' is not assignable to type 'ChangeEvent<HTMLInputElement> | undefined - for the code snippet below: const App = () => { const [ mont ...

Methods for transforming a TypeScript class instance containing getter/setter properties into a JSON format for storage within a MySQL database

I am currently working on a TypeScript class that includes a getter and setter method: export class KitSection { uid: string; order: number; set layout(layout: KitLayout) { this._layout = new KitLayout(layout); } get layout( ...

React, Storybook - Error TS2307: Button module not found or its type declarations. Can Storybook resolve this issue?

In my React project, I have a Button component created with "create-react-app" that uses absolute paths for importing. When trying to import { Button, ButtonProps } from 'Button', I encountered an error with TS2307. The absolute path 'Butto ...

The FullCalendar does not appear as expected on Angular version 16

https://i.stack.imgur.com/DTAKr.pngI followed the steps to install FullCalendar in my Ionic 6 Angular 16 app as outlined on https://fullcalendar.io/docs/angular. However, nothing is showing up in the browser (chrome). The Inspector tool shows that the Ful ...