'Assigning value to select by patching a form
I have this select:
<select class="form-select form-select-md" formControlName="MaritalStatus">
<option value="0" selected>Select...</option>
<option *ngFor="let option of maritalStatusList" [ngValue]="option">{{ option.name }}</option>
</select>
I have a list, which is what I'm using for the options. Then, the selected option I save it in the form by means of the formControlName. I'm using ngValue because option is an object, and I want to store the whole object instead of just the ID. It works fine, but when I try to patch the value the selected value is not appearing in the select.
I patch a whole bunch of values at the same time, but this is basically what it would look like:
this.form.patchValue({ MaritalStatus: MaritalStatus });
And the MaritalStatus object I would be patching would look like this:
export class MaritalStatus {
id: number;
name: string = '';
createdAt: string = '';
updatedAt: string = '';
deletedAt: string = '';
}
What I want to accomplish is that when I patch that MaritalStatus object, it appears selected in the select, whose list of options is a list of MaritalStatuses. I hope I'm making sense.
Solution 1:[1]
So I managed to fix it with a solution that I don't like so much, but so far it is the only thing that worked. What I did was that I looked for the object that contains the ID that I wanted to patch inside the list. So assume that ms is the MaritalStatus object that I want to patch.
this.form.patchValue({ MaritalStatus: this.maritalStatusList.find(x => x.id === ms.id) })
And it is working perfectly. I'm not sure why directly patching the value isn't working, as it saves me that find, but I'll go with that until I find something better.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | plasmy |
