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

In Typescript, the module source is imported rather than the compilation output

I created a custom module for personal use and decided to host it on a private GitHub repository. Within the module, I have included a postinstall script that runs: tsc -d -p .. Currently, the generated .js and .d.ts files are located alongside the source ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

Keep track of the input values by storing them in an array after they are

Creating an Angular application to read barcodes. barcode-scanner.component.html <form #f="ngForm" class="mt-3 text-center" id="myform" (ngSubmit)="onSubmit(f)"> <div class="text-center"> <input type="text" maxlength= ...

What is the best way to send put and delete requests through a form using node.js and express.js?

Attempting to send a put request: Put form code snippet: <form id="for" action="/people" method="post"> <div class=""> <input type="text" name="Name" value=<%= data[0].name %> > </div> ...

The interplay between javascript and PL/SQL tasks in a dynamic scenario

I'm attempting to run multiple pl/sql blocks within a Dynamic Action, providing real-time feedback to the user through a modal dialog displaying the current status. Here is an example of what I am trying to achieve: Processing Step 1... /*Run pl/s ...

Please refrain from submitting the form until the slow AJAX jQuery process has finished

My form is experiencing a delay of almost 4 seconds due to the Ajax jQuery I am using, which creates fields within the form. This delay causes some users to submit the form before the necessary fields are created. I need a way to prevent the form from bein ...

Error: "Access-Control-Allow-Origin" header is missing in Firebase Function

I have encountered an issue with my firebase functions GET request. While I am able to receive data using Postman, I am facing difficulties when trying to fetch data from my front-end application. Upon accessing the endpoints, I am seeing the following er ...

Tips for including a decimal point in an angular reactive form control when the initial value is 1 or higher

I am trying to input a decimal number with 1 and one zero like 1.0 <input type="number" formControlName="global_velocity_weight" /> this.form = this.fb.group({ global_velocity_weight: new FormControl(1.0, { validators: [Valida ...

Learning how to effectively utilize the tap and map functions in Angular

How can I redirect to a URL received from the backend in my Angular project? public createPaymentMethod(paymentMethodDto: any): Observable<any> { return this.http.post<any>(ConfigService.Configuration.apiUrl + `/payments`, paymentMetho ...

In order to use the serve command, it is necessary to run it within an Angular project. However, if a project definition cannot be located

An error occurred while running the ng serve command: C:\Mysystem\Programs\myfwms>ng serve The serve command needs to be executed within an Angular project, but a project definition could not be found. I encounter this error when ...

After installing the latest version of Node.js, the stability of the Ionic environment

After updating nodejs from v8.1 to v12, my ionic environment is experiencing instability. Any suggestions on what needs to be updated? [abc]$ ionic cordova emulate android When running ng run app:ionic-cordova-build --platform=android, an unhandled exce ...

Using Node.js, express, jade, highcharts, and a 2D array

Greetings, I am relatively new to the realm of javascript/node.js/express/jade/highcharts etc... The predicament at hand is as follows: I have a template that takes in a few parameters which are pre-processed in my router code. These parameters are group ...

How can a property be made mandatory in Typescript when another property is set as optional?

Currently, I am unsure about what to search for in order to fulfill the following requirement. Specifically, I am utilizing the given type for react props: interface ComponentProps { message : string, minValue? : number, minValueValidationMessage? ...

Center the popover over the element

I am in the process of creating a resource map using SVGs. My goal is to display a popover in the center of the element when a user clicks on it. However, due to CSS rotation of the map, the traditional techniques such as the one mentioned here have not be ...

Turning off form validation in AngularJS for a short period of time

Successfully implemented client side form validation using AngularJS, but now I want to test my server side validation by sending incorrect data. However, AngularJS is preventing me from doing so! Is there a way around this without disabling Javascript an ...

Nested data selection in React

I have been experimenting with creating a nested select optgroup and attempted the following: const data = [ { sectorId: 5, sectorName: "Sector One", departments: [ { deptName: "Production", jobtitles: [ { ...

Hear and register keypress in Angular service

I offer a dialog service Check it out below @Injectable() export class HomeDialogService { public constructor(private readonly dialogService: DialogService, private readonly userAgent: UserAgentService) {} @HostListener('document:keydown.escape ...

The Mongoose query for the id field retrieves both the id and _id values

Within my Mongoose schema, there is a specific field named id which holds a unique identifier for each document. This operates using the same system as the standard _id field as shown below: var JobSchema = new mongoose.Schema({ id: { type:String, requi ...

When working with formControlName in Angular Material 2, the placeholder may overlap the entered value

After updating my application with angular-cli to angular/material (2.0.0-beta.11) and angular (4.4.4), I noticed that every placeholder in the material input fields overlaps the value when provided with formControlName in reactive forms. However, when usi ...

The Redux Toolkit Slice is encountering an issue where it generates the incorrect type of "WritableDraft<AppApiError> when the extraReducer is

I defined my initial state as MednannyAppointments[] for data and AppApiError for error. However, when I hover over state.error or state.data in my extraReducer calls, the type is always WritableDraft. This behaviour is confusing to me. Even though I have ...