typescript 错误类型错误:无法设置null的属性(设置“value”)

kadbb459  于 2023-04-22  发布在  TypeScript
关注(0)|答案(1)|浏览(410)

我知道这个问题已经讨论过here,但我找不到一个可以帮助我的答案。在一个表单中,我有一个输入:

<mat-form-field class="example-full-width" appearance="fill">
  <mat-label>Database Name</mat-label>
    <input [disabled]="isValueSelected_SQLite()" id="numeDB_SQLite" type="text" matInput
           placeholder="Ex: Lite_DB" name="numeDB_SQLite" ngModel required=""
           oninvalid="this.setCustomValidity('Please enter DB name')"
           oninput="setCustomValidity('')">
</mat-form-field>

ngAfterViewInit函数中,我想给输入字段赋值:

ngAfterViewInit() {
  (document.getElementById("numeDB_SQLite") as HTMLInputElement).value = "dt";
}

当我打开页面时,我得到错误:ERROR TypeError: Cannot set properties of null (setting 'value') .我搜索浏览器的元素,字段的id为numeDB_SQLite。我尝试使用ngOnInit方法而不是ngAfterViewInit。我可以做些什么来解决这个错误?

ql3eal8s

ql3eal8s1#

在html上:

<mat-form-field class="example-full-width" appearance="fill">
                 <mat-label>Database Name</mat-label>
                       <input [disabled]="isValueSelected_SQLite()" id="numeDB_SQLite" type="text" matInput
                                    placeholder="Ex: Lite_DB" name="numeDB_SQLite" [(ngModel)]="dt" required=""
                                    oninvalid="this.setCustomValidity('Please enter DB name')"
                                    oninput="setCustomValidity('')">
         </mat-form-field>

关于 typescript :

dt: string = "";  
ngAfterViewInit() { dt= "this appears on field" }

相关问题