如何动态过滤字符串列表?
我发现了ng-repeat
的示例,但是它不适用于角度7 :它不加载任何字符串,仅适用于ngFor
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">Find ticket</div>
</div>
<input class="form-control" placeholder="Insert ticket to find" [(ngModel)]="find_text">
</div>
<ul class="list-group" style="max-height: 200px; overflow: auto;">
<li class="list-group-item" *ngFor="let s of find_text">{{s.Value}}</li>
</ul>
答案 0 :(得分:1)
You're binding find_text as a string in ngModel and as a list of Objects in *ngFor directive. I think this is what you're asking:
public text;
private word_list = [{value:"Apple"}, {value:"Banana"}, {value:"Pear"}, {value:"Bluebarry"}]
get find_text(){
return this.word_list.filter(x => x.value.toLowerCase().includes(text.toLowerCase()));
}
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">Find ticket</div>
</div>
<input class="form-control" placeholder="Insert ticket to find" [(ngModel)]="text">
</div>
<ul class="list-group" style="max-height: 200px; overflow: auto;">
<li class="list-group-item" *ngFor="let s of find_text">{{s.value}}</li>
</ul>
答案 1 :(得分:0)
借助管道
HTML代码:
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">Find ticket</div>
</div>
<input type="text" class="form-control" [(ngModel)]="searchText" placeholder="Search item" name="search"
autocomplete="off">
</div>
<ul class="list-group" style="max-height: 200px; overflow: auto;">
<li class="list-group-item" *ngFor="let s of word_list| filterForUser : searchText">{{s.value}}</li>
</ul>
过滤器:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filterForUser'
})
export class FilterPipeForUserSearch implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if (!items || !searchText) return items;
searchText = searchText.toLowerCase();
// return items.filter(it => {
return items.filter((data) => this.matchValue(data,searchText));
// });
}
matchValue(data, value) {
return Object.keys(data).map((key) => {
return new RegExp(value, 'gi').test(data[key]);
}).some(result => result);
}
}
组件:
private word_list = [{value:"Chiku"}, {value:"Apple"}, {value:"Banana"}, {value:"Pear"}, {value:"Bluebarry"}]
注意:请在您的应用模块中声明FilterPipeForUserSearch
。