2

I am trying to find a way to mark the option as selected in my select but I am not successful.

I tried several solutions found over internet but couldn't find the right implementation.

Does any one have a working example, thanks.

Below (part of) my code

.html

<form [formGroup]="fgForm">
...
<select class="form-control" formControlName="country">
    <option value="" [ngValue]="null">Choose your country</option>
    <option 
        *ngFor="let oneCountry of selOptCountries;" 
        [ngValue]="oneCountry"
    >{{oneCountry.name}}</option>
</select>
</form>

.ts (formControl)

// The data comes from an API
this.selOptCountries = [
{"id": 2516, "name": "Austria", "iso2": "AT"},
{"id": 2519, "name": "Belgium", "iso2": "BE"},
{"id": 2523, "name": "Bulgaria", "iso2": "BG"},
{"id": 2601, "name": "Croatia", "iso2": "HR"},
...
{"id": 2636, "name": "Luxembourg", "iso2": "LU"}
...
];

this.fgForm = this.formBuilder.group({
'country': [
        {value: datas.country,disabled: false},
        [Validators.required]
    ],
});

datas.country

{id: 2636, name: "Luxembourg", iso2: "LU"}
NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Jean-Philippe M
  • 731
  • 1
  • 7
  • 19

3 Answers3

2

Instead of setting the value with datas.country directly, write it as like this:

value: this.selOptCountries.find(c => c.id === datas.country.id)

Demo

https://stackblitz.com/edit/object-option-item?file=src/app/app.component.ts

The datas.country object and the country object(Luxembourg) in the countries are not recognized as same though they have exactly same properties since every object in JavaScript is unique.

From MDN


In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

critrange
  • 5,652
  • 2
  • 16
  • 47
1

If you are setting your select option value as object instead of id etc then you need to use compareWith directive to compare the value.

<form [formGroup]="fgForm">
 <select class="form-control" formControlName="country" [compareWith]="selectedVal">
<option [ngValue]="">Choose your country</option>
<option 
    *ngFor="let oneCountry of selOptCountries;" 
    [ngValue]="oneCountry"
>{{oneCountry.name}}</option>
</select>

in .ts

selectedVal(valOne, valTwo ) : boolean {
  return valOne.id === valTwo.id;
}

Working DEMO

Kamran Khatti
  • 3,754
  • 1
  • 20
  • 31
0

The clean and correct way to do this is to use the ngModel binding on the select tag.

Here is an answer I submitted on another post, with reference and working Stackblitz example:

https://stackoverflow.com/a/64082745/450388

Adamski
  • 839
  • 2
  • 10
  • 28