0

app.component.html

<input type="text" placeholder="data" aria-label="Number" matInput [formControl]="organisationControl" [matAutocomplete]="auto" > <mat-autocomplete #auto="matAutocomplete" [displayWith]=" displayFn" (optionSelected)='onOrgChange($event.option.value)'> <mat-option *ngFor="let option of filteredOptions| async | sort: 'name'" [value]="option"> {{option 。姓名}}

app.component.ts

1. import { SortPipe } from "../../../pipes/sort.pipe";
2. private sortPipe: SortPipe,

app.module.ts

1. import { SortPipe } from '../../pipes/sort.pipe';
2.@NgModule({
  declarations: [
        SortPipe
  ], 
   providers: [SortPipe]

定制管道

共享 --> 管道 --> sort.pipe.ts

import { Injectable, Pipe, PipeTransform } from '@angular/core';
export type SortOrder = 'asc' | 'desc';

@Injectable()
@Pipe({
  name: 'sort',
})
export class SortPipe implements PipeTransform {
  transform(value: any, sortOrder: SortOrder | string = 'asc', sortKey?: string): any {
    sortOrder = sortOrder && (sortOrder.toLowerCase() as any);

    if (!value || (sortOrder !== 'asc' && sortOrder !== 'desc')) return value;

    let numberArray = [];
    let stringArray = [];

    if (!sortKey) {
      numberArray = value.filter(item => typeof item === 'number').sort();
      stringArray = value.filter(item => typeof item === 'string').sort();
    } else {
      numberArray = value.filter(item => typeof item[sortKey] === 'number').sort((a, b) => a[sortKey] - b[sortKey]);
      stringArray = value
        .filter(item => typeof item[sortKey] === 'string')
        .sort((a, b) => {
          if (a[sortKey] < b[sortKey]) return -1;
          else if (a[sortKey] > b[sortKey]) return 1;
          else return 0;
        });
    }
    const sorted = numberArray.concat(stringArray);
    return sortOrder === 'asc' ? sorted : sorted.reverse();
  }
}

问题:它不是按升序显示的。有什么我想输入的吗?

4

1 回答 1

0

为具有方向的管道和要在 app.component.html 中应用排序的字段名称提供适当的参数,sort如下所示:

<mat-option *ngFor="let option of filteredOptions| async | sort: 'asc':'name'" [value]="option"> {{option.name}}

参考stackblitz的例子

于 2021-04-17T07:20:46.930 回答