Set value of selected in dropdown in Angular 2

2019-07-13 12:07发布

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>

I tried this

this._commServe.addExternalCompany(company).subscribe((data) => {   
  this.formUser.value.externalCompany = company.CompanyName;
}, (error) => {
  this.errorMessage = <any>error;
})

I also tried using ngModel which also didn't work as expected.

What would the best way be of setting the selected state of this dropdown without resorting to jQuery for example

1条回答
孤傲高冷的网名
2楼-- · 2019-07-13 12:40

You can set the selected attribute on an option that has the selected value in the model.

[attr.selected]="selectedExternalCompany"

Using that the html template:

<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>

And in the component set the selectedExternalCompany when the select box change and use that as the model for instance.

This is based on the answer How to add conditional attribute in Angular 2?

查看更多
登录 后发表回答