问题描述
我正在使用FormBuilder向数据库添加值。
I am using FormBuilder to add values to a DB.
this.formUser = this._form.group({
"firstName": new FormControl('', [Validators.required]),
"lastName": new FormControl('', [Validators.required]),
"externalCompany": new FormControl('', [Validators.required])
})
在添加这些值之前我想将下拉列表(外部公司)的值设置为我事先提交的值
Before adding these values I want to set the value of a dropdown(external company) to to value that I submitted beforehand
<select class="form-control" id="companyExternal" formControlName="externalCompany" (ngModelChange)=onChangeExternalC($event)>
<option value="" >Select existing company...</option>
<option value="{{company}}" *ngFor="let company of externalCompanies">{{company}}</option>
<option value="Company name..." >ADD ANOTHER...</option>
</select>
我尝试了此
this._commServe.addExternalCompany(company).subscribe((data) => {
this.formUser.value.externalCompany = company.CompanyName;
}, (error) => {
this.errorMessage = <any>error;
})
我也尝试过使用ngModel,但也无法按预期工作。
I also tried using ngModel which also didn't work as expected.
在不使用jQuery的情况下设置此下拉列表的选定状态的最佳方法是什么?示例
What would the best way be of setting the selected state of this dropdown without resorting to jQuery for example
推荐答案
您可以在具有以下内容的选项上设置 selected
属性
You can set the selected
attribute on an option that has the selected value in the model.
[attr.selected]="selectedExternalCompany"
使用html模板:
<select class="form-control" id="companyExternal" formControlName="externalCompany" (ngModelChange)=onChangeExternalC($event)>
<option value="" >Select existing company...</option>
<option value="{{company}}"
*ngFor="let company of externalCompanies"
[attr.selected]="selectedExternalCompany"
>{{company}}</option>
<option value="Company name..." >ADD ANOTHER...</option>
</select>
然后在组件中设置 selectedExternalCompany
选择框更改并将其用作示例。
And in the component set the selectedExternalCompany
when the select box change and use that as the model for instance.
这基于答案
这篇关于在Angular 2的下拉菜单中设置选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!