简体   繁体   中英

Set value of selected in dropdown in Angular 2

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM