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