选择时区时,我想实现一项功能。 当我在输入字段中键入任何值时,该列表将过滤其结果。因此,该列表将缩小为仅包含我在其中键入的内容的子列表。
例如:
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,因此无法正常工作。
感谢任何帮助。
答案 0 :(得分:1)
ngOnInit() {
this.timezoneList = momentTZ.tz.names();
this.originalTimezoneList = momentTZ.tz.names();
}
filterList(e) {
this.timezoneList = originalTImezonelist.filter(x => x.includes(e)
}
答案 1 :(得分:1)
您可以使用“角度自定义管道”来实现。请检查此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);
});
}
}