问题描述
我有一个包含用户名的下拉菜单.我想按字母顺序排序.我怎样才能做到这一点?
I have a dropdown with user names. I would like to order it alphabetically. How can I achieve this?
<md-select formControlName="user" id="user" style="min-width: 200px;">
<md-option *ngFor="let user of users" [value]="user.id">
{{user.displayName}}
</md-option>
</md-select>
推荐答案
您可以为此构建自定义 OrderBy
管道.
you can build a custom OrderBy
Pipe for this.
例如,下面的 OrderBy Pipe 将按您传递给它的 key
对 object array 进行排序,按字母顺序或基于值(顺序:asc):
For example the below OrderBy Pipe will sort the object array by the key
you passed to it with alphabetically or value based (order: asc):
@Pipe({name: 'OrderBy'})
export class OrderByPipe implements PipeTranform {
transform(input: any, key: string) {
if (!input) return [];
return input.sort(function(itemA, itemB) {
if (itemA[key] > itemB[key]) {
return 1;
} else (itemA[key] < itemB[key]) {
return -1;
} else {
return 0;
}
});
}
}
在您的模板中,如下所示:
and in your template as below:
<md-option *ngFor="let user of users | OrderBy: 'id'" [value]="user.id">`
不要忘记在 NgModule
的 declarations
中添加 OrderByPipe
.
don't forget to add OrderByPipe
to your declarations
of NgModule
.
UPD:
如@DeborahK 和角度附录的回答 无 FilterPipe 或 OrderByPipe(最后一部分),OrderBy
使用不纯的 Pipe 可能会导致性能问题,所以这里我提供了一个纯 Pipe,这意味着您可以确定何时触发 OrderBy Pipe这是给输入数组一个新的实例或改变转换为管道的参数.
as answered by @DeborahK and angular appendix No FilterPipe or OrderByPipe(last part), OrderBy
with a impure Pipe may cause performance problem, so here I'm providing an pure Pipe which means you can determine when to fire the OrderBy Pipe which is give the input Array a new instance or change the parameter transformed to the Pipe.
这篇关于Angular Material - 按字母顺序下拉排序项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!