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.name}}

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]

Custom Pipe

Shared --> pipe --> 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();
  }
}

Question: It is not displayed in ascending order. is there anything I missed to input?

1 Answer 1

-1

Provide proper arguments for your sort pipe having direction and the field name on which sorting is to be applied in app.component.html as given below:

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

Refer the example of stackblitz

Sign up to request clarification or add additional context in comments.

1 Comment

The Stackblitz isn't an Angular Material Autocomplete.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.