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"}
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.