为什么不能使用getElementById在HTML的选择列表中设置预选值?

时间:2019-04-02 09:07:11

标签: html angular typescript angular7 getelementbyid

我正在尝试根据上一个选择列表设置一个预选选项(该部分未在下面显示)。当我在getelementById()字段而不是<input>上使用它时,它可以与<select>一起使用。这是为什么?

工作示例:

<label for="goalcategory">Edit assigned category</label>
        <select id="selectedGoalcategory" class="form-control" required>
          <option></option>
          <option *ngFor="let goalcategory of allGoalcategories">{{goalcategory.description}}</option>
        </select>

        <input class="input" style="width:10%;" id="TestInput" type="text"/>

后面的打字稿:

getCategoriByGoal()
  {
    var preSelectedGoalcategory = this.selectedGoal.goalcategory;

    this.selectedGoalcategory = preSelectedGoalcategory;

    (<HTMLInputElement>document.getElementById("TestInput")).value = 
    this.selectedGoalcategory.description;

  }

我希望它的工作方式(HTML):

<label for="goalcategory">Edit assigned category</label>
        <select id="selectedGoalcategory" class="form-control" required>
          <option></option>
          <option *ngFor="let goalcategory of allGoalcategories">{{goalcategory.description}}</option>
        </select>

我希望它的工作方式(脚本):

getCategoryByGoal()
  {
   var preSelectedGoalcategory = this.selectedGoal.goalcategory;

    this.selectedGoalcategory = preSelectedGoalcategory;

    (<HTMLInputElement>document.getElementById("selectedGoalcategory")).value = 
    this.selectedGoalcategory.description;

  }

2 个答案:

答案 0 :(得分:1)

如果您不介意添加第3方组件,则可以添加ng-select,这会使您在很多事情上的生活变得更加轻松。 从npm安装ng-select:

npm install --save @ng-select/ng-select

之后,将其与FormsModule一起添加到您的模块中:

import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent],
  imports: [NgSelectModule, FormsModule],
  bootstrap: [AppComponent]
})
export class AppModule {}

在HTML中,您可以像这样使用它:

 <ng-select [items]="allGoalcategories" bindLabel="name" bindValue="id" name="goalcategories"
                        [(ngModel)]="selectedGoalcategory">
 </ng-select>

现在,每次更改selectedGoalcategory时,它将反映在您的其他下拉列表中,并且您无需使用getElementById

答案 1 :(得分:0)

正如@wentjun所说,在这种情况下,不需要依赖document.getElementById()。 要获取下拉菜单的值,您需要将“ selectedGoalcategory”绑定到下拉菜单,然后执行以下操作:

<select [(ngModel)]="selectedGoalCategory">
  <option></option>
  <option *ngFor="let goalcategory of goalCategories" [value]="goalcategory.id">{{ goalcategory.name }}</option>
</select>

因此,“预选择”一个值,只需将“ dropDownValue”的值设置为下拉列表中的值之一即可。

我不确定为什么需要输入字段,但是如果您希望输入字段反映下拉菜单的值,则可以这样做:

<input class="input" style="width:10%;" id="TestInput" type="text" [(ngModel)]="selectedGoalCategory" />