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;
}