What is causing the error message to appear even though the element has been correctly defined? - TypeError: Unable to access the value property of null

Objective: Obtain the value of an HTML element in TypeScript (Angular)

Issue: Error: Uncaught (in promise): TypeError: Cannot read property 'value' of null

Error Message: TypeError: Cannot read property 'value' of null at UserRegistration2Component.push../src/user-registration-2.component.ts.UserRegistration2Component.getTranslations (user-registration-2.component.ts:649) at UserRegistration2Component.push../src/user-registration-2.component.ts.UserRegistration2Component.createForm (user-registration-2.component.ts:509) at new UserRegistration2Component (user-registration-2.component.ts:484)

Code at line 649:

this.spanishHidden = (<HTMLInputElement>document.getElementById("hiddenInputLs")).value;

Context/Steps Taken: I have successfully executed similar operations on multiple other components/pages without any issues. However, I am now encountering this error unexpectedly on this particular component. I attempted to relocate the hidden input element within the HTML structure but it did not resolve the error. (Note: The elements are hidden as part of i18n translation and should not be visible on the page). Additionally, I tried renaming and duplicating the IDs to rule out typos or duplicates, yet the error persisted. I reviewed solutions provided here and experimented with various approaches, but the error persists (Why am I getting "TypeError: Cannot read property 'value' of null" when using getElementById?). Is there a minor syntax issue that I may have overlooked?

HTML Code Snippet:

<mat-card class="login-card">


<mat-card-title class="text-center" i18n="@@Something_H1_1">
    New User Registration
</mat-card-title>
<mat-card-subtitle class="text-center" i18n="@@Something_H1_2">
    Step 1 of 4
</mat-card-subtitle>



<mat-card-content>
    <input placeholder="Spanish" id="hiddenInputLs" i18n-value="@@Something_H1_30" value="Spanish" [hidden]="true">
    <input placeholder="English" id="hiddenInputLe" i18n-value="@@Something_H1_31" value="English" [hidden]="true">

    <form [formGroup]="_userRegForm2" (ngSubmit)="cmdRegisterUser_click()" novalidate>

        <div fxLayout fxLayout.xs="column" fxLayoutAlign="center" fxLayoutGap="30px" class="columns">
            // more code here......
        </div>

    </form>

TypeScript Code Snippet:

createForm()
    {
        this.getTranslations();
        this.languages = [
            { value: 'English', viewValue: this.englishHidden },
            { value: 'Spanish', viewValue: this.spanishHidden }
        ];
    }

getTranslations() {
    this.spanishHidden = (<HTMLInputElement>document.getElementById("hiddenInputLs")).value;
    this.englishHidden = (<HTMLInputElement>document.getElementById("hiddenInputLe")).value;
}

Answer №1

Here are a few recommendations to consider:

  1. Avoid directly manipulating the DOM and instead use Angular's provided interfaces, such as Renderer or ViewChild.
  2. Depending on where the method getTranslations is called from, the view may not have finished rendering yet. If called from the component constructor or ngOnInit hook, the element may not have been created.
  3. Avoid accessing the value of a search method (getElementById) directly, as the element may not be available. This can lead to errors in your JavaScript code and potentially cause problems for your application. It's better to check if the element exists before accessing its properties.
  4. There appears to be an issue with the line for the English input in the template at the end of it.

Please let me know if you still encounter difficulties extracting the value after trying these suggestions.

Answer №2

It was necessary for me to include this code block within ngAfterViewInit(). I must admit, I am unsure as to why it functioned properly on all other pages even without using ngAfterViewInit. Nevertheless, here is the solution implemented:

ngAfterViewInit() {
    this.retrieveTranslations();
}

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

Is it possible to verify type property names using a union type?

Given type UnionType = 'prop1' | 'prop2' | 'prop3'; type DerivedType = { prop1: string; prop2: number; prop3: boolean; }; Is there a method to define DerivedType in such a way that if I introduce a new member to UnionT ...

Utilizing an Express server instead of Lite server in combination with Angular 2 RC

Looking to develop a single page application using the latest Angular 2 RC and an Express server, but unsure how to connect them without utilizing Bower, Gulp, and Webpack. I have explored some starter packs but haven't found one that meets my expecta ...

I am looking for an Angular Observable that only returns a single value without any initial value

Is there a way to create an Observable-like object that calls a webservice only once and shares the result with all subscribers, whether they subscribe before or after the call? Using a Subject would provide the result to subscribers who subscribed before ...

Angular 6 - configuring HTTP requests, creating authentication services, implementing request interceptors

I am currently in the process of setting up the token login service, HTTP service, and interceptor (for setting headers) for the first time. I'm encountering some difficulties as Angular 6 differs from version 5. Here is the code snippet for my Login ...

Is it possible to show elements from an ngFor loop just once when dealing with a two-dimensional string array in a display?

I have an array of nested strings, and I am attempting to display the contents of each inner array in a table format. My goal is to have the first table show the values from the first index of each inner array and the second table to display the values fro ...

Issues with updating in Firebase real-time database using Angular 2 are not

I am currently working on a simple app that inserts new records into Firebase. Below the input field, the app lists the last 10 items in the database. ISSUE: I am facing a problem where I have to start inputting something in the input field or click on ...

Tips for creating an operation within a JSON document?

Today, I am attempting to customize the appearance of my audiobook list. However, when trying to add an aspectRatio key-value pair to each object in my JSON file, I encountered an error. https://i.stack.imgur.com/Qb3TX.png https://i.stack.imgur.com/qTkmx. ...

Chrome autocomplete behaves as if the input fields are disabled and cannot be clicked on

I am experiencing an unusual issue with autofill in Chrome. After logging in and then logging out of the app, the input fields (email, password) are auto-filled but appear to be frozen and unclickable. This problem does not occur every time; it only happe ...

Ensuring proper extension of Request headers in Typescript

I am having trouble retrieving the userId from req.headers, how can I fix this issue? Initially, I attempted the following: interface ISpot{ thumbnail: File, company: string, price: number, techs: string } interface IReqCustom<T& ...

Encountering the error "unrecognized pseudo-class :lang" following the Angular update

Recently, I updated my node version and encountered a new error: custom-file-input:lang(en)~.custom-file-label -> unmatched pseudo-class :lang I'm not sure what's causing this issue. Can someone help me troubleshoot this error? My current n ...

TS2339: The attribute 'size' is not present on the 'string' data type

Within my Typescript file, I have the following line: return stringToValidate.length <= maxLength; Despite the code executing without issues, an error is displayed: TS2339: Property 'length' does not exist on type 'string'. I am cu ...

What could be causing TypeORM to create an additional column in the query

Why does this TypeORM query produce the following result? const result6 = await getConnection() .createQueryBuilder() .select('actor.name') .from(Actor,'actor') .innerJoin('actor.castings',&apos ...

Angular2 error: "missing exported member 'bootstrap'"

Upon opening my Atom editor, I encountered the following message: The issue of 'Module '"C:/express4/node_modules/@angular/platform-browser-dynamic/index"' not exporting member 'bootstrap' raised at line 2 col 10 This warning a ...

You cannot employ typed arguments in combination with Typescript within the VueJS framework

I'm struggling to develop a typescript vue component with some methods. Here is the script snippet. <script lang="ts"> import Vue from 'vue'; export default Vue.extend({ methods: { check(value: number) { console.log(valu ...

What is the best way to display images when a single element in a list created by ngFor is hovered over in Angular 2

displayStar(val) { this.starDisplayed = true; } <ul class="listboxtickets"> <li class="selectlistticket" *ngFor="let item of ticketList" (mouseover)="displayStar(item.id)" (mouseleave)="hideStars()"> <div class="ticket ...

Organizing Firebase functions: Managing multiple functions and dependencies

Objective I aim to gain a deeper understanding of how the firebase CLI manages the deployment process for multiple firebase functions, each stored in different files, and how it handles dependencies that are specific to certain functions. Situation If I ...

Can you explain the distinction between Array<string> and string[]?

Can you explain the contrast between Array<string> and string[]? var companies: Array<string> = ['Samsung', 'Sony', 'LG']; var businesses: string[] = ['Lenovo', 'Asus', 'Acer']; ...

The functionality of Angular 9 Service Worker appears to be inhibited when hosting the site from a S3 Static Website

I created a Progressive Web Application (PWA) following these steps: Started a new Angular app using CLI 9.1.8; Added PWA support by referring to the documentation at https://angular.io/guide/service-worker-getting-started; Built it with ng build --prod; ...

Declaring a function type with a void parameter type in typescript

Embarking on my journey with ts and currently exploring TypeGraphQL. I came across something that caught my attention and seems unfamiliar to me: export declare type ReturnTypeFunc = (returns?: void) => ReturnTypeFuncValue; How should this type be unde ...

Unshifting values in a JavaScript array only if they exist in another array

I have two arrays of objects - one containing selected data and the other containing general data that needs to be displayed General data for display const arr = [ { id: "1", name: "Skoda - Auto" }, { id: "2" ...