GolfBravo
GolfBravo

Reputation: 1117

Angular Reactive Forms unable to get formControlName to set value on an ngFor template loop

I am using Angular reactive forms and I am trying to get a form control value to set as default value on a drop-down list. I am able to get this to work if I do not use the *ngFor loop in my template code. However, I need to use this as I will have many options in the tag.

    <select formControlName="staffName">
       <option>Bob Jason</option>
       <option>Sally Reel</option>
       <option>Jack Jones</option>  
       <option>George Smith</option>  
       <option>Harry Lake</option>  
    </select>

However, if I use the code below, it does not work

     <select formControlName="staffName">
        <option *ngFor="let StaffMemberModel of StaffMemberModels">
            {{StaffMemberModel.firstName}} {{StaffMemberModel.lastName}}
        </option>      
     </select>

The StaffMemberModel is an array of that that contains id, firstName, and lastName as shown below.

enter image description here

It outputs the below. However, it only shows the first option in the drop-down, when it should show the staff member that has been selected in the previous page.

enter image description here

Upvotes: 0

Views: 905

Answers (1)

MrRobot
MrRobot

Reputation: 1167

You can do it so by passing the [value]="StaffMemberModel.id" flag.

It can be firstName, lastName, ID, whatever you want.

<form [formGroup]="form">
  <select formControlName="staffName">
    <option *ngFor="let StaffMemberModel of StaffMemberModels"
    [value]="StaffMemberModel.id" > 
      {{ StaffMemberModel.firstName }} {{ StaffMemberModel.lastName }}</option>
  </select>
</form>

If you want to see it in action: https://stackblitz.com/edit/angular-w8bjyl

Upvotes: 1

Related Questions