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.Using that the html template:
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?