Reputation: 4033
I have the following code to display a selection of countries:
<div class="col">
<select name="country" id="country" class="form-control" ngModel required>
<option *ngFor="let country of countries; let i = index" [selected]="country.name.common === 'United States'" [value]="country.name.common">{{country.name.common}}</option>
</select>
<img src="/assets/images/icons/chevron-down.svg" alt="Dropdown" class="chevron-icon">
</div>
On init the component fetches its data from a JSON file inside of my assets folder. It works - the selection with its countries is being displayed. How am I able to determine a preselected value.
As you can see, my approach was to set a [selected]
with a condition, but it doesn't work. Changing it to solely [selected]="country.name.common"
, will preselect the list's last country.
Upvotes: 0
Views: 30
Reputation: 10662
In your component.ts
use the the name for your select and assign it to your desired value like:
countries.map((country) => {
if(country.name.common === 'United States') {
// assign here
}
})
Upvotes: 0
Reputation: 10429
You have to remove ngModel
so your code should be
<select name="country" id="country" class="form-control" required>
<option *ngFor="let country of countries; let i = index" [selected]="country.name.common === 'United States'" [value]="country.name.common">{{country.name.common}}</option>
</select>
OR
Remove selected
attr and set [(ngModel)]="selectedCountry"
and set in componenet.ts selectedCountry="countryname"
Demo
Upvotes: 1