首页 > 解决方案 > 为什么在正确设置元素时会出错?- TypeError:无法读取 null 的属性“值”

问题描述

目标:在 TypeScript (Angular) 中获取 HTML 元素的值

问题:错误:未捕获(承诺中):TypeError:无法读取 null 的属性“值”

TypeError:无法在 UserRegistration2Component.push 的 UserRegistration2Component.push../src/user-registration-2.component.ts.UserRegistration2Component.getTranslations (user-registration-2.component.ts:649) 处读取属性“值”。 ./src/user-registration-2.component.ts.UserRegistration2Component.createForm (user-registration-2.component.ts:509) 在新的 UserRegistration2Component (user-registration-2.component.ts:484)

第 649 行的代码

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

背景/我尝试过的:我在其他几十个组件/页面上做了同样的事情,没有问题。我不确定为什么我突然在这个错误上遇到这个错误。我尝试将隐藏的输入元素移动到 html 的不同部分,但它并没有改变结果。(注意:它是隐藏的,因为我正在使用 i18n 进行翻译并且不希望这些项目显示在页面上。同样,我已经在其他几十个页面上成功完成了此操作)我还尝试重命名 ID 并复制粘贴它们以确保没有某种拼写错误或重复,但仍然是同样的错误。我在这里查看了解决方案并尝试了各种可能性,但我仍然收到错误消息(为什么我收到“TypeError:无法读取 null 的属性'值'”)。我错过了像语法这样的小东西吗?

HTML

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

打字稿

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

标签: angulartypescriptnull

解决方案


我不得不把它放在 ngAfterViewInit() 中。老实说,我不确定为什么这在没有 ngAfterViewInit 的所有其他页面上都有效。但这就是我所做的:

ngAfterViewInit() {
    this.getTranslations();
}

推荐阅读