0

根据 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>

4

1 回答 1

0

当您将数据分配给您的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

于 2022-02-28T05:23:03.360 回答