3

Here I got a list of countries in an autocomplete dropdown and tried to filter those by starting letters of the country name.

Example: If we type "Aus", all the country name with "aus" are being filtered. (See screenshot). I want to filter only "Australia and Austria" or any other country names with starting letters "Aus".

How to do that?

enter image description here

<ng-autocomplete #countryList formControlName="locationCountry" [data]="countries"
   min-length="1" [searchKeyword]="countrykeyword"
   [initialValue]="countrykeyword"
   (selected)='selectEventCountry($event);onLocationSubmit();'
   (inputCleared)='onCountryCleared($event, false)'
   [itemTemplate]="countryListTemplate"
   [notFoundTemplate]="notFoundTemplate" placeHolder="Enter Country">
</ng-autocomplete>
2
  • you can use custom pipe , check this solution stackoverflow.com/a/49670236/10607908 Commented Jun 15, 2021 at 6:24
  • It's impossible for me know "what" autocomplete you're using, check if there'r a way to reemplace the "search function" -if there're an @Input or similar-
    – Eliseo
    Commented Jun 15, 2021 at 6:25

1 Answer 1

8

According to Angular AutoComplete Inputs,

Input Description
customFilter Custom filter function. You can use it to provide your own filtering function, as e.g. fuzzy-matching filtering, or to disable filtering at all (just pass (items) => items as a filter). Do not change the items argument given, return filtered list instead.

You can define your custom filter logic and pass it to [customFilter] @Input property.


SOLUTION

.component.html

<ng-autocomplete #countryList formControlName="locationCountry" 
    [data]="countries" 
    min-length="1"
    [searchKeyword]="countrykeyword" 
    [initialValue]="countrykeyword"
    (selected)='selectEventCountry($event);onLocationSubmit();' 
    (inputCleared)='onCountryCleared($event, false)'
    [itemTemplate]="countryListTemplate" 
    [notFoundTemplate]="notFoundTemplate" 
    placeholder="Enter Country"
    [customFilter]="customFilter">
</ng-autocomplete>

.component.ts

export class AppComponent {
  ...

  customFilter = function(countries: any[], query: string): any[] {
    return countries.filter(x => x.name.toLowerCase().startsWith(query.toLowerCase()));
  };
}

Sample Solution on StackBlitz

2
  • Hi, How to I call API to get data in customFilter()? I got an error: core.mjs:6495 ERROR TypeError: Cannot read properties of undefined Many thanks. Commented Jun 28, 2022 at 6:24
  • Hi @NguyenPhong, perhaps try to create a new question and provide the minimal code, error and sample data for reproduction purposes. Look forwards to your question. Thanks.
    – Yong Shun
    Commented Jun 28, 2022 at 7:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.