如何按名称对列表进行排序?

时间:2018-07-10 11:32:22

标签: angular

我正在使用角度反应形式,并希望按字母顺序对下拉列表中的数据进行排序。

这是我的代码:

<md-select placeholder="Select Cost Center" required formControlName="costCenterId" [(ngModel)]="selectedCostCenter">
        <md-option *ngFor="let costCenter of costCenters" [value]="costCenter.costCenterId">
          {{ costCenter.costCenterName }}
        </md-option>
      </md-select>

3 个答案:

答案 0 :(得分:0)

您必须在代码中对成本中心进行排序。

this.costCenters.sort((a, b) => a.costCenterName.localCompare(b.costCenterName));

答案 1 :(得分:0)

Use material autocomplete

HTML:

<form class="example-form">
  <mat-form-field >
    <input type="text" placeholder="Filter Name" aria-label="Assignee" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option.name}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

TS:

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

export interface User {
  name: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular 6';
  myControl = new FormControl();
  options: User[] = [
    { name: 'Mary' },
    { name: 'Masy' },
    { name: 'Maty' },
    { name: 'Mvry' },
    { name: 'Mbry' },
    { name: 'Shelley' },
    { name: 'Igor' }
  ];
  filteredOptions: Observable<User[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
      startWith<string | User>(''),
      map(value => typeof value === 'string' ? value : value.name),
      map(name => name ? this._filter(name) : this.options.slice())
      );
  }

  displayFn(user?: User): string | undefined {
    return user ? user.name : undefined;
  }

  private _filter(name: string): User[] {
    const filterValue = name.toLowerCase();

    return this.options.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
  }
}

答案 2 :(得分:0)

尝试以下代码段: 您无需更改TS文件,只需复制此代码并将其粘贴。

    <md-select placeholder="Select Cost Center" required formControlName="costCenterId" [(ngModel)]="selectedCostCenter">
        <md-option ng-value="costCenter.costCenterId" ng-repeat="costCenter in costCenters | orderBy:costCenterName">{{ costCenter.costCenterName }}</md-option>
    </md-select>