Error in Typescript: Uncaught TypeError: Unable to access the `value` property of null at HTMLButtonElement.document.getElementById.addEventListener.event

Hello, I'm facing an issue with a simple Typescript calculator and I can't seem to figure out what's causing the problem. I'm puzzled as to why I'm receiving a null value because the element IDs appear to be correct.

HTML :

X: <input type="text" id="x" > &nbsp;
Y: <input type="text" id="y" >
<br>

<button  id="Add">Add</button> &nbsp;&nbsp;
<button  id="Subtract">Subtract</button>

<span id="output"></span>

TS:

window.onload = function() {
    var calc = new Calculator('X','Y','Output');
}


class Calculator {
    private x: HTMLInputElement;
    private y: HTMLInputElement;
    private output: HTMLSpanElement;

    constructor(xId: string, yId:string,outputId:string) {
        this.x = <HTMLInputElement>document.getElementById(xId);
        this.y = <HTMLInputElement>document.getElementById(yId);
        this.output = <HTMLSpanElement>document.getElementById(outputId);
        this.wireEvents();
    }

    wireEvents() {
        document.getElementById('Add').addEventListener('click',event => {
            this.output.innerHTML = this.add(parseInt(this.x.value), parseInt(this.y.value)).toString()
        });
        document.getElementById('Subtract').addEventListener('click',event => {
            this.output.innerHTML = this.subtract(parseInt(this.x.value), parseInt(this.y.value)).toString();
        });
    };

    add(x:number,y:number) {
        return x+y;
    }
    subtract(x:number,y:number){
        return x-y; 
    }

}

Answer №1

Typographical Error: Lowercase versus Uppercase

Within your HTML, the id attributes are written in lowercase

X: <input type="text" id="x" > &nbsp;
Y: <input type="text" id="y" >

However, in your TypeScript code, you have them in uppercase

var calc = new Calculator('X','Y','Output');

Since the id attribute is case-sensitive, using document.getElementById will result in undefined

// At this point, this.x will be undefined
this.x = <HTMLInputElement>document.getElementById(xId);

Resolution

To fix this issue, simply replace X with x and Y with y

 var calc = new Calculator('x','y','Output');

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

Unexpected behavior observed in ng-select when pasting search values

When attempting to update an array of strings acting as the model for an ng-select, the values do not appear correctly in the search box. https://i.sstatic.net/WqdJ6.png The values that are displaying correctly are the ones selected from the dropdown men ...

Exploring the Functionality of Backend Objects in Frontend TypeScript within the MEAN Stack Environment

Utilizing MongoDB, express.js, angular4, node.js Although a string I retrieve is successful, it's not the same as retrieving the full object... account.service.ts (full, ) import { Injectable } from '@angular/core'; import { Http, Headers ...

Troubleshooting: Angular add/edit form issue with retrieving data from a Span element within an ngFor loop

I am currently working on an add/edit screen that requires submitting a list, among other data. The user will need to check 2-3 checkboxes for this specific data, and the saved record will have multiple options mapped. Here is what the HTML looks like: &l ...

Utilizing Typescript in Angular to dynamically change mat-radio-button options

I am experiencing a successful operation with my mat-radio-button component. However, my goal is to programmatically select the correct button once I receive the necessary parameters. Below is the HTML code snippet: <form [formGroup]="seaso ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

Surprising Media Component Found in URL Parameters within the design

Exploring the page structure of my Next.js project: events/[eventId] Within the events directory, I have a layout that is shared between both the main events page and the individual event pages(events/[eventId]). The layout includes a simple video backgro ...

Mapping properties between objects in Typescript: transferring data from one object to another

Here are two different types and an object: type TypeX = { x: number; y: number; z: number; }; type TypeY = { u: number; v: number; w: number; }; initialObject: { [key: string]: TypeX }; The goal is to transfer the properties from an object of ...

Utilize Angular's Reactive Form feature to track changes in Form Control instances within a Form Array and calculate the total value dynamically

I am currently utilizing Angular Reactive Forms to loop through an array of values and I want to include a total field after the Form Array that automatically updates whenever there are changes in the Form Array control values. Here is some sample data: ...

What is the significance of var-less variables in TypeScript class definitions?

Why is it that when creating a component class in Angular2, we don't need to use var when declaring a new variable? For example: @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> ` }) export class AppCo ...

The retrieval of cookies from the Response object is not possible with Typescript

While working on my google chrome extension, I implemented a post call that looks like this: public someapiCall(username: string, password: string) { var url = 'http://test.someTestServer.com/api/user/someApiCall'; let headers = new Hea ...

The first argument passed to CollectionReference.doc() must be a string that is not empty

I'm facing an issue with my Ionic app while attempting to update records in Firebase. The error message I keep encountering has me stumped as to where I might be going wrong. Error: Uncaught (in promise): FirebaseError: [code=invalid-argument]: Functi ...

Data cannot be transferred to a child element unless it has been initialized during the definition phase

Passing an array data from parent to child component has brought up some interesting scenarios: parent.component.html: <child-component ... [options]="students" > </child-component> Status I: Setting the array on definition ...

Modifying the color of the chosen item - ion-select

Can anyone help me with changing the color of the selected item on ion-select? I've tried several solutions without success. Any suggestions? Documentation: https://ionicframework.com/docs/api/select I attempted to use the color property, but it did ...

Strategies for transferring data from index.html to component.ts in Angular 4

Greetings, as a newcomer to Angular, I am seeking advice on how to link my Index.html file to component.ts. Please review the code snippet below where I have created a function called scannerOutput in my Angular index.html file which is functioning properl ...

Angular: Granting an external module access to a provider

One of the modules I imported provides a service with an optional dependency. Although it being optional didn't affect my application, as it just prevented any errors from occurring when not present. Here's an example: import { FooModule } from ...

Issue with `rxjs/Subject.d.ts`: The class `Subject<T>` is incorrectly extending the base class `Observable<T>`

I found a sample template code in this helpful tutorial and followed these two steps to get started - npm install // everything went smoothly, created node_modules folder with all dependencies npm start // encountered an error as shown below- node_mo ...

Is it possible to effortlessly associate a personalized string with an identifier within an HTML element utilizing Angular2?

Check out this cool plunker import {Component} from 'angular2/core' @Component({ selector: 'my-app', template: ` <div *ngFor="#option of myHashMap"> <input type="radio" name="myRadio" id="{{generateId(option[& ...

Angular: Using ngrx for Nested HTTP Calls

Looking at my Angular code, I am trying to figure out how to convert nested HTTP calls into the ngrx pattern. My idea is to create separate actions for getUser and getPost, but I am struggling with passing the getUser response as a parameter to the getPo ...

The 'xxx' type is lacking various properties compared to the 'xxx[]' type, such as length, pop, push, concat, and many others

Utilizing typescript and reactjs, the issue lies within this component import type { InputProps } from "../utils/types" const Input = (props: InputProps) => { const makeChildren = () => { return ( <> ...

Utilizing Typescript generics with an optional second parameter

Learning about generics in typescript has been quite challenging for me. However, I was able to make it work successfully. export type Events = { LOGIN: undefined NAVIGATION: { screen: string } SUPPORT: { communication_method: 'chat&ap ...