user2863754
user2863754

Reputation: 13

Why can't I set a select option programmatically when using an object on a Reactive Form in Angular

I'd like to figure out because I can't set the select option of a Reactive Form using the following typescript code:

That's my class

export class SlotStatusTypes {
    id: number;
    description: string;
}

That's my component template

<select id="subject" formControlName="subject" class="form-control"
   aria-describedby="subject">
   <option *ngFor="let statusType of slotStatusTypesList" [ngValue]="statusType">
      {{statusType.description}}
   </option>
</select>

And that's in my component:

slotStatusTypesList: SlotStatusTypes[] = [];

The slotStatusTypesList variable is filled in by another HTTP GET call.

Here I initialize my form:

ngOnInit(): void {
   this.slotForm = new FormGroup({
      ...
      subject: new FormControl(null, [
        Validators.required
      ]),
      ...
   });
}

Within a callback function is filled in the slotForm form among which the subject field after finding the value corresponding as you can see below:

let statusTypeFound: SlotStatusTypes = this.slotStatusTypesList.find(r => r.id === slotPlanning.statusTypeId);

this.slotForm.setValue({
   ...
   subject: statusTypeFound,
   ...
});

Up to now it all works.

Now, I want to set an identical object of type SlotStatusTypes in the slotForm form instead of looking for an object by a list, see below:

let slotStatusType: SlotStatusTypes = {
   id: slotPlanning.id, //id: 1
   description: slotPlanning.description //description: "Available"
};

this.slotForm.setValue({
   ...
   subject: slotStatusType,
   ...
});

At this point the slotForm form select isn't set with the selected value as I expected.
Why doesn't it work in that case?

Upvotes: 0

Views: 851

Answers (1)

mimo
mimo

Reputation: 6817

I believe your problem is here, when creating new slotStatusType object.

let slotStatusType: SlotStatusTypes = {
   id: slotPlanning.id,
   description: slotPlanning.description
};

It is a new object with a new reference, that does not exists in slotStatusTypesList array. So select cannot match any item in the list with slotStatusType, although properties id and description are the same.

To setValue of FormControl you need to use item from slotStatusTypesList array. I am not sure if you can avoid searching for it, but you can optimize your code to save a reference of an item once you find it.

Upvotes: 3

Related Questions