TS2339 error: The element of type 'HTMLElement' does not contain a property called 'imageID'

Struggling to utilize the global variable imageID to retrieve the value of getImage, but consistently encountering the error "Property 'imageID' does not exist on type 'HTMLElement'.". Desire to assign the HTMLELement to the global variable imageID. Is there a way to convert the variable to a string or another data type? Any recommendations or suggestions are greatly appreciated.

dashboard.component.ts

 import {Component,Input,OnChanges,OnInit,SimpleChanges} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {Emotion} from 'emotion';
import {EmotionService} from 'emotion.service';



@Component({
    selector: 'dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
    emotions: Emotion[] = [];
    emotion: string;
    imageID: any;
    constructor(private emotionService: EmotionService) {}

    ngOnInit() {
        this.getEmotions();
       // this.makeMatch();

        //function to randomize and get face images
        var w = document.getElementById('wrapper');
        var button = document.getElementById('randomize');
        var images = w.children; // inner elements, your image divs
        // a function to hide all divs
        var hideDivs = function(imgs: HTMLCollection) {
            for (var img of < any > imgs) {
                (img as HTMLElement).style.display = 'none';
            } //for
        } //hideDivs

        hideDivs(images); // hide all initially

        button.addEventListener('click', function(event) {
            console.log('');
            console.log('%c=============================', "color: blue");
            console.log('%c In getFaces method', "color: blue", );
            var rnd = Math.floor(Math.random() * images.length); // get random index
            hideDivs(images); // hide all images

            (images[rnd] as HTMLElement).style.display = 'block'; // show random image
            (event.target as HTMLElement).textContent = 'Click one more time!';
            var getImage = (images[rnd] as HTMLElement);


                    //where error occurs
           this.imageID = getImage.id;


            // this.imageID as HTMLElement = images[rnd].getAttribute('alt');
              console.log('%c Image ID for match making: ', imageID );
            console.log('%cImage ID: ', "font-weight: bold", getImage.id);
           // console.log('%cAll image data:', "font-weight: bold", images[rnd]);
            console.log('%c=============================', "color: blue");
            console.log('');

        }) //button

Answer №1

The issue arises because the comparison of this === button in your code

button.addEventListener('click', function(event) {
       ...
       this.imageID = getImage.id;
       ...
    })

To declare imageID as a global variable, you can simply use window

window.imageID = getImage.id;

If you prefer assigning imageID to a class instance attribute, utilize bind

button.addEventListener('click', function(event) {
       ...
       this.imageID = getImage.id;
       ...
    }.bind(this))

Alternatively, you can use an arrow function

button.addEventListener('click', (event) => {
       ...
       this.imageID = getImage.id;
       ...
    })

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

How to Submit a Form in jQuery with both File and Text inputs without Redirecting the Current Window

I am working on creating an application form that allows users to attach images. The form consists of a few input elements placed within a div rather than a traditional form element. I need the form to be submitted via AJAX without causing a page redirect, ...

issue with bootstrap modals single firing when using remote data source

I am facing an issue with my table that contains a list of items, each item having a <select> element with different statuses. Here's how the process is supposed to work: Upon changing the status, a modal should pop up. The modal suc ...

Verify whether the user is authenticated in a Vue single-page application and redirect them to the login page if not

My VueJS single-page application uses JWT authentication for users. I am currently working on ensuring that users remain authenticated after a page reload. If the user is not authenticated, they should be redirected to the login page. The access token an ...

Choosing an option from an HTML dropdown menu within an Android WebView

Can someone provide me with an example of how to use JavaScript to select an item from an HTML drop-down menu after downloading a webpage to WebView? ...

Overseeing the management of JavaScript dependencies

Our website is plagued with old frontend code that's in disarray. It's a mishmash of different versions of JavaScript frameworks and libraries being loaded. Some parts of the code have messy inline JavaScript that attempts to handle dependencies ...

Ways to determine if prototype methods vary

Is there a technique to verify if functions are distinct despite originating from the same prototype? I'm inquiring because I want to save functions in an array, and when attempting to delete one, it removes all functions due to sharing prototypes. ...

I lose my user interface after a series of clicking events

I've created a React application that generates new quotes without repetition, but I'm encountering an issue where the UI disappears after clicking enough times. What could be causing this behavior in my code? The console displays an object error ...

Retrieving Outdated Information through the Express Framework

Whenever I make a fetch request to a node express server, it sometimes returns old data that was previously fetched from the same endpoint. This issue occurs sporadically but seems to happen more often than not. Even after disabling Cache-Control in the f ...

Routing in Node.js does not navigate to every internal route within an Angular application

I am currently developing a frontend application using Angular 9. In order to run the application, I have set up a NodeJs server to handle all incoming requests and direct them to the Angular Dist (Build) files. Issue at Hand The main problem I am facing ...

Sequencing State Changes in React Components

import { useState } from 'react'; function App() { const [number, setNumber] = useState(0); function clickHandler() { setNumber((n) => { console.log('First updater function'); return n + 1; }); setNumber ...

Submit information with Ajax in multipart/form format

Here is the HTML code I have: <form:form name="vcfForm" id="vcfForm" method="post" enctype="multipart/form-data" action="../acquaintance/readingContactsFromVcfFile"></form:form> <input type="file" name="vcfFile" id="vcfFile" form="vcfForm" ...

Struggling to display my array data retrieved from the database on my Angular 5 page

I hope everyone is doing well. I am currently facing a problem with retrieving data from Firebase. I have an array within an array and I want to display it in my view, but I am encountering difficulties. Let me share my code and explain what I am trying to ...

The basic structure for organizing components and categories

I am working on creating a list and have designed the following Schema: new SimpleSchema({ element: { type: String, optional: true }, note: { type: String, optional: true }, order: { type: Number, optional: true } }); Now, I wan ...

Having difficulty understanding Symbol.iterator and the return value type in a for-of loop while using TypeScript

Currently, I am delving into type script and embarking on a journey to learn how to craft generic containers for educational purposes. I have developed a LinkedList class with the intention of incorporating the ability to iterate over it, like so: for (co ...

Python code allowing users to navigate back to the previous page while retaining elements

After my script scrapes the page, it automatically clicks a button if a new element meeting certain criteria is found. Everything works perfectly when there is only one element, but an issue arises when the button click leads to a new page opening. If ther ...

Coordinating a series of maneuvers

When it comes to coordinating multiple sequential actions in Redux, I find it a bit confusing. I have an application with a summary panel on the left and a CRUD panel on the right. My goal is to have the app automatically update the summary after a CRUD op ...

Determine the size of a file in either megabytes or kiloby

I need to determine the size of a file in either megabytes if the value is greater than 1024 or kilobytes if less than 1024. $(document).ready(function() { $('input[type="file"]').change(function(event) { var _size = this.files[0].si ...

How can I fill the data array of arrays using an Angular Table component?

I am struggling to populate an Angular Table with data in the array of arrays format. Despite my efforts, the code I have written does not seem to work. Any suggestions for a solution would be greatly appreciated. Here is the data that I am trying to popu ...

The recommended filename in Playwright within a Docker environment is incorrectly configured and automatically defaults to "download."

Trying to use Playwright to download a file and set the filename using download.suggestedFilename(). Code snippet: const downloadPromise = page.waitForEvent('download', {timeout:100000}) await page.keyboard.down('Shift') await p ...

Applying selected values to the scope without the need for ng-options definition

Currently, I am attempting to extract values from a select element and incorporate them into the scope while ensuring that they remain updated. Typically, this task would be achieved using ng-model without any issues. However, in this particular scenario, ...