I have a telephone prefix code dropdown select box, which is populated from a database. I currently have an alphabetical dropdown list containing the country names & dial codes eg. UK (+44), etc.
Ideally I would like to place the top 4 most popular countries (UK, US, France, Spain) at the top of the list (with the full list following them), however I'm unsure how & where to filter this list. Potentially using an optgroup tag and using ngFor to loop through the countries.
component.html
<select
class="block appearance-none text-gray-600 w-full"
[(ngModel)]="value.code" name="code" (change)="modelChange($event)">
<option *ngFor="let country of countries" [value]="country.phoneCode">
{{ country.name + ' (+' + country.phoneCode + ')'}}
</option>
</select>
service.cs
public IList<CountryViewModel> GetCountries()
{
using (var db = new ApplicationDbContext())
{
var countries = db.Countries.OrderBy(x => x.Name).ToList();
return mapper.Map<List<Country>, List<CountryViewModel>>(countries);
}
}
In TypeScript you can do something like this to sort it
Countries.sort((a, b)=> +['UK', 'US', 'France', 'Spain'].includes(b.name))
However be aware that sort
does not mutate the existing array, it just returns a new sorted array, which you can then use in your html to bind to the select box
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.