[英]Filter list by md-autocomplete Angular 4
我要在選擇時區時實施一項功能。 當我在輸入字段中鍵入任何值時,該列表將過濾其結果。 因此,該列表將縮小為僅包含我在此處鍵入的內容的子列表。
例如:
lsit = ["apple", "orange", "applepie", "appletart","pie","orangetart"];
因此,當我鍵入“ apple”時,列表將縮小為
["apple", "applepie", "appletart"];
以下代碼是我對html文件所做的操作
<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文件
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;
}
因為timezoneList包含如下結果:
["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers",
"Africa/Asmara","Africa/Asmera", "Africa/Bamako", ...........]
因此,我在鍵入時應該如何過濾此列表。 我嘗試按照Angular文檔進行操作,但是由於我的Angular版本為4,因此無法正常工作。
感謝任何幫助。
ngOnInit() {
this.timezoneList = momentTZ.tz.names();
this.originalTimezoneList = momentTZ.tz.names();
}
filterList(e) {
this.timezoneList = originalTImezonelist.filter(x => x.includes(e)
}
您可以使用“角度自定義管道”來實現。 請查看此https://codeburst.io/create-a-search-pipe-to-dynamically-filter-results-with-angular-4-21fd3a5bec5c了解詳細信息。
在您的app.component.ts中:
<input ng-model="searchText" placeholder="enter search term here">
<ul>
<li ng-repeat="c in list | filter : searchText">
{{ c }}
</li>
</ul>
在你的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);
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.