如何按字母顺序对下拉值进行排序



根据Angular文档,没有orderBy管道可用于排序。根据文档,我必须自己在组件中实现排序。由于我是Angular的新手,我不确定该怎么做。有人能帮忙吗?我正在寻找实际的代码,这将做到这一点。

我想按升序对发卡行下拉列表进行排序。ts文件如下

import { Component, OnInit } from '@angular/core';
import { IssuerDropdownService } from './service/issuer-dropdown.service';
import { DisputeDataSessionService } from 'src/app/service/dispute.session.service'
@Component({
selector: 'app-issuer-dropdown',
templateUrl: './issuer-dropdown.component.html',
styleUrls: ['./issuer-dropdown.component.scss']
})
export class IssuerDropdownComponent implements OnInit {
constructor(public issuerService: IssuerDropdownService, public session: DisputeDataSessionService) { }
issuerList: any = [];
ngOnInit(): void {
this.issuerService.getIssuerList().subscribe(res => {
this.issuerList=res.data;
})
}
selectIssuer(issuer) {
this.issuerService.issuer = issuer.issuerName;
this.session.setSubscriberId(issuer.subscriberId);
this.session.setCountryCode(issuer.issuerCountryCode);
}
}
<mat-form-field appearance="outline" >
<mat-label translate>Issuer</mat-label>
<mat-select placeholder="Choose an Issuer"  [(ngModel)]="this.issuerService.issuer" class="issuerSelectPanel">
<mat-option (click)="selectIssuer(issuer)" *ngFor="let issuer of issuerList" [value]="issuer.issuerName" >{{ issuer.issuerName }}</mat-option>
</mat-select>             
</mat-form-field>

将数据分配给issuerList时,需要对数据进行排序。

function sortByName(a: any, b: any) {
var nameA = a.issuerName.toUpperCase(); // ignore upper and lowercase
var nameB = b.issuerName.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
}

this.issuerService.getIssuerList().subscribe(res => {
this.issuerList = res.data.sort(this.sortByName);
})

Javascript工作示例:

function sortByName(a, b) {
var nameA = a.issuerName.toUpperCase(); // ignore upper and lowercase
var nameB = b.issuerName.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
}
var someList = [{issuerName: "John"}, {issuerName: "Jane"}, {issuerName: "bob"}];
someList.sort(sortByName);
console.log(someList);

请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

相关内容

  • 没有找到相关文章

最新更新