在Angular 2的下拉菜单中设置选定的值 [英] Set value of selected in dropdown in Angular 2

查看:163
本文介绍了在Angular 2的下拉菜单中设置选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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中添加条件属性?

这篇关于在Angular 2的下拉菜单中设置选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆