I need to access the link_id value from this specific actionid and then execute the corresponding function within the Ionic framework

I have a JavaScript code in my TypeScript file. It retrieves the attribute from a span element when it is clicked. I want to store this attribute's value in a TypeScript variable and then call a TypeScript function.

Take a look at my ngOnInit method, all I need is to assign the value of link_id to this.actionid and then invoke the callpagedata() function.

Here is the JavaScript code inside my home.ts:

actionid;
 ngOnInit(){
var mainDiv = document.getElementById("mainDiv");
mainDiv.addEventListener("click", function (event) {
  console.log("Inside Event Listener");
  event.preventDefault();
    var link_id = $(event.target).attr("action");
    console.log("Actionid is:: " + link_id);
});
}

All I want is to have the value of link_id stored in this.actionid and then be able to call the callpagedata() function. I attempted using this.actionid = linkId but encountered issues with accessing actionid within the event listener and link_id outside of it.

callpagedata(){

}

The HTML code found in home.html is as follows:

<div id="mainDiv">
  <span action="10004">Quick Task</span>
  <span action="10006">Quick Patrol</span>
</div>

Answer №1

In an event handler, you might want to reference the 'this' object which represents the current event listener object. To achieve this, assign the main function's 'this' object to a variable like this_parent = this, and then access it using this_parent.actionid:


    actionid;
    ngOnInit(){
        var mainDiv = document.getElementById("mainDiv");
        let this_parent = this;
        mainDiv.addEventListener("click", function (event) {
            console.log("Inside Event Listener");
            event.preventDefault();
            var link_id = $(event.target).attr("action");
            console.log("Actionid is:: " + link_id);
            this_parent.actionid = link_id;
    });
    }

Answer №2

If you're looking to avoid using jQuery, I suggest incorporating Angular instead.

However, if you prefer sticking with your current code, you can achieve the desired outcome like this:

In Typescript:

ngOnInit(){
    var mainDiv = document.getElementById("mainDiv");
    mainDiv.addEventListener("click", function (event) {
      console.log("Inside Event Listener");
      event.preventDefault();
        console.log(event.target);
        var link_id = (<HTMLElement>event.target).getAttribute('action');
        // in TypeScript, we need to specify that event.target is an HTMLElement.
        console.log("Actionid is:: " + link_id);
    });
}

I tested this code and it functions properly. Nonetheless, I highly recommend utilizing Angular Events, which would look something like this:

In HTML:

<div id="mainDiv">
  <span (click)="myFunction(10004)">Quick Task</span>
  <span (click)="myFunction(10006)">Quick Patrol</span>
</div>

In Typescript:

myFunction(value: number): void {
    console.log('my value', value);
}

I trust this information proves beneficial to you.

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

Passing a property to a click event handler in ES6 with React: What's the best approach?

Struggling with passing props to a click function in my React learning journey. I'm attempting to make a basic ES6 counter component that increases when a button is clicked. The click function I have so far is: click() { this.setState({ c ...

Triggering a dynamically created event with the onchange event

I'm currently working on creating an input type file, and here is the code I have: var element = document.createElement("INPUT"); element.type = "file"; element.id = "element" + i; $("#media").append("<br>"); $("#media").append("<br>"); $ ...

Display a free Admob banner within an Ionic 3 application

I have integrated Admob's banner into my Ionic 3 app following the guidelines provided in the Ionic documentation at this link. Below is the code snippet I used for displaying the banner on the homepage: import { Component } from '@angular/core ...

The readyState of Ajax is consistently anything but 4

I have encountered an issue with my JavaScript code. I am running these codes in order to display data based on user input. Despite there being no error connection and the connection happening properly, whenever I enter a name it always goes into the else ...

Every div must have at least one checkbox checked

Coding in HTML <div class="response"> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> </div> <div class="response"> <input type="check ...

The radio buttons are stuck and not changing their selection

Having a group of radio buttons with the same name, when one is checked, it automatically selects another one in the group. Here is my current code: <input name="a" type="radio"> <input name="a "type="radio" checked> JS $("input[type='r ...

Creating a like and dislike button using Jquery's ajax functionality

Hey everyone, I'm currently working on implementing a like and dislike button similar to Facebook's on my website. I have a list of posts displayed using PHP loops and I want a single button to change color to blue if liked and remain the default ...

Stop HTML audio playback upon clicking on a specific element

I'm looking to add background music to my website with a twist - a music video that pops up when the play button is clicked. But, I need help figuring out how to pause the background music once the user hits play. Play Button HTML - The play button t ...

I haven't encountered any type warnings in the places where I anticipated them

When I define an object like this: const x: { str: string, num: number } = { str: str, num: not_a_num }; I am surprised to find that even though 'not_a_num' is a string and not a number, the compiler does not throw an error. Instead, ...

What are the distinctions between generic and discriminated types?

Hi there, I've been thinking of an idea but I'm not sure how to implement it or if it's even possible. Is there a way to create a type SomeType where the first property can be any value from the set T, but the second property cannot be the ...

Obtain cell information when clicking on a specific field within a material-table

import MaterialTable from "material-table"; import ShipmentContext from "../context/ShipmentContext"; const ItemsTable: React.FC = () => { const shipmentcontext = useContext(ShipmentContext); const { filtered } = shipmentcontex ...

Is all of the app fetched by Next.js when the initial request is sent?

After doing some research online, I learned that Next.js utilizes client-side routing. This means that when you make the first request, all pages are fetched from the server. Subsequent requests will render those pages in the browser without needing to com ...

A dynamic Angular component consisting of two distinct rows to be seamlessly integrated into an existing table

I'm currently working on a component called "template" that can consist of either two rows. @Component({ selector: '[my-row]', template: ` <tr> <td>first</td> <td>second</td> </tr> <t ...

Using backslashes to escape JSON values within a value in Angular

When retrieving JSON data from the backend, I often encounter an issue where the value is set to "key": "\$hello" and it results in an "Unexpected token d". Is there a way in Angular to handle or escape these characters once received from the server? ...

Generating Javascript code with PHP and handling quotes successfully

After encountering an issue with apostrophes causing errors in my PHP-generated HTML, I found a solution that involved using the addslashes() function. Here is the code snippet: <?php $lines = array(); $lines[] = "I am happy"; $lines[] = "I'm hap ...

Angular JS effectively prevents redundant data from being displayed to users when scrolling infinitely while also efficiently removing DOM elements for previous data

I'm currently working on implementing AngularJS Infinite Scroll without using jQuery. My goal is to display the first 3 data items when the page loads and then load the next 3 data items from a JSON array object as the user scrolls. The issue I am fac ...

What are the steps for combining two constants with the JSON format of "const = [ { } ]"?

Here is the initial code that I would like to merge with another section. const sections = [ { title: section1_title, rows: [{ title: section1_option01, rowId: "sec1_option01", ...

Integrate a button following the first paragraph exclusively when there are two or more paragraphs present

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> jQuery(document).ready(function($) { if ( $('p').length < 1 ) { $('p:last-child').after('<div id="toggle" class="btn"> ...

Discover the new method for establishing fixed column widths in the PrimeNG table now that the Autolayout property is no longer in use

Previously, I was able to customize the width of th elements in the primeng table template by using style="width: 25%". However, it seems that this feature is no longer supported and the documentation now mentions that autolayout is deprecated, resulting ...

After two HTML injections, Javascript ceases to function properly

I am in the process of developing a chat feature for my website. The layout includes a conversation section on the left and a list of users on the right. When a user's div is clicked, their ID is transmitted to the Django back end. Subsequently, full ...