[英]Populating a dropdown list from a database with selected items then the rest in alphabetical order
I have a telephone prefix code dropdown select box, which is populated from a database.我有一个电话前缀代码下拉框 select 框,它是从数据库中填充的。 I currently have an alphabetical dropdown list containing the country names & dial codes eg.
我目前有一个按字母顺序排列的下拉列表,其中包含国家名称和拨号代码,例如。 UK (+44), etc.
英国(+44)等
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.理想情况下,我想将最受欢迎的 4 个国家/地区(英国、美国、法国、西班牙)放在列表顶部(完整列表紧随其后),但是我不确定如何以及在何处过滤此列表。 Potentially using an optgroup tag and using ngFor to loop through the countries.
可能使用 optgroup 标记并使用 ngFor 遍历国家/地区。
component.html组件.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服务.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在 TypeScript 你可以做这样的事情来排序
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但是请注意,
sort
不会改变现有数组,它只会返回一个新的排序数组,然后您可以在 html 中使用它来绑定到 select 框
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.