Search code examples
angularformsdrop-down-menu

How can I programatically change the selected option in a select in angular forms without using DOM queries


Given the following html block:

<div *ngIf="isProfessional" class="form-group d-flex flex-column ml-5" id="professionalType">
    <label class="mb-0">Professional Type</label>
    <select class="form-select" formControlName="professionalType">
        <option value="" disabled selected>Choose a type</option>
        <option *ngFor="let item of sortedProfessionalTypeCodesData" [ngValue]="item.code">
            {{ item.display }}
        </option>
    </select>
</div>

I have to make an http request to get a list of items that will be used to populate the dropdown:

this.scheduleApiService.getSchedules(userClinicLocation.id, this.scheduleForm.controls["professionalType"]?.value || undefined, "PROF")
  .subscribe((schedules: Schedule[]) => {
    this.professionalTypeCodes = schedules;
    this.sortedProfessionalTypeCodesData = professionalTypeCodes.sort((pt1, pt2) => pt1.display < pt2.display ? -1 : (pt1.display > pt2.display ? 1 : 0));
    // TODO - Select the first option
  })

Where this.sortedProfessionalTypeCodesData is the sorted list I'm feeding the component. I want dropdown to display the first element of the list.

How can I change the selected option? Keep in mind the form has already been initialized so I can't do things like:

this.scheduleForm = this.formbuilder.group({
  ...
  professionalType: [this.myList[0], Validators.required],
  ...
})

Solution

  • I've managed to find a solution:

    this.scheduleForm.controls["professionalType"].setValue(this.sortedProfessionalTypeCodesData.length > 0 ? this.sortedProfessionalTypeCodesData[0].code : undefined)
    

    The mistake I was making was passing the whole object to the setValue function. However, since in the html I mapped the item.code field as value, it wasn't working. By passing the code to the function, it makes the mapping automagically. Unfortunately, I don't know angular well enough to explain how that happens