Alex
Alex

Reputation: 143

Filter list by md-autocomplete Angular 4

I want to implement a feature when selecting timezone. The list will filter its result as I type any value in the input filed. So the list will narrow down to a sublist only contains the what I typed there.

For example:

lsit = ["apple", "orange", "applepie", "appletart","pie","orangetart"];

so when I type "apple", then the list will narrow down to

["apple", "applepie", "appletart"];

The following code is what I did on my html file

<md-input-container class="full-width">
   <input name="timezone" type="text" [(ngModel)]="timezone" 
     (ngModelChange)="filterList($event)" placeholder="Select your timezone"
      mdInput [mdAutocomplete]="auto" class="full-width" required>

   <md-autocomplete #auto="mdAutocomplete" (optionSelected)='getDetails($event.option.value)'>
       <md-option *ngFor="let t of timezoneList" [value]="t">
           {{ t }}
       </md-option>
   </md-autocomplete>
</md-input-container>

ts file

timezoneList;
timezone;

ngOnInit() {
 this.timezoneList = momentTZ.tz.names();
}

getDetails(e) {
  console.log(e) . // this will capture the option result 
}

filterList(e) {
  console.log(e) // this will capture the input result
                 // type a, then e = a;
                 // type ap, then e = ap;
                 // type apple, then e = apple;
}

Because the timezoneList contains result like:

 ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers",  
  "Africa/Asmara","Africa/Asmera", "Africa/Bamako", ...........]

So how should I filter this list while I am typing. I tried to follow the Angular docs, but since my angular version is 4, it is not working properly.

Appreciate any help.

Upvotes: 1

Views: 490

Answers (2)

Wen W
Wen W

Reputation: 2647

ngOnInit() {
 this.timezoneList = momentTZ.tz.names();
 this.originalTimezoneList = momentTZ.tz.names();
}

filterList(e) {

  this.timezoneList = originalTImezonelist.filter(x => x.includes(e)
}

Upvotes: 1

Kevin
Kevin

Reputation: 302

You can do it by using Angular Customized Pipe. Please check this https://codeburst.io/create-a-search-pipe-to-dynamically-filter-results-with-angular-4-21fd3a5bec5c for full details.

in your app.component.ts:

<input ng-model="searchText" placeholder="enter search term here">
  <ul>
    <li ng-repeat="c in list | filter : searchText">
      {{ c }}
    </li>
  </ul>

in your filter.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if(!items) return [];
    if(!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter( it => {
      return it.toLowerCase().includes(searchText);
    });
   }
}

Upvotes: 1

Related Questions