我正在尝试根据之前的选择列表设置一个预先选择的选项(该部分未在下面显示)。当我在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>
我希望它的工作方式(Typescript):
getCategoryByGoal()
{
var preSelectedGoalcategory = this.selectedGoal.goalcategory;
this.selectedGoalcategory = preSelectedGoalcategory;
(<HTMLInputElement>document.getElementById("selectedGoalcategory")).value =
this.selectedGoalcategory.description;
}
如果您不介意添加第三方组件,您可以添加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
正如@wentjun所说,没有必要依赖document.getElementById()来实现这种情况。要获取下拉列表的值,您需要将“selectedGoalcategory”绑定到下拉列表,然后按照以下步骤操作:
<select [(ngModel)]="selectedGoalCategory">
<option></option>
<option *ngFor="let goalcategory of goalCategories" [value]="goalcategory.id">{{ goalcategory.name }}</option>
</select>
因此,“预先选择”一个值,您只需将“dropDown Value”的值设置为下拉列表中的某个值。
我不确定为什么你需要输入字段,但如果你想让输入字段反映下拉列表的值,那么你会这样做:
<input class="input" style="width:10%;" id="TestInput" type="text" [(ngModel)]="selectedGoalCategory" />