我想在我的打字稿中使用result,以便我可以将搜索管道的长度输出到父组件。
<span *ngFor ="let data of posts | filter : search as result >
{{result.length}}
</span>
过滤管:
transform(value: any[], args?: any): any[] {
if(!value)return null;
if(!args)return value;
var listofItems ;
args = args.toLowerCase();
listofItems = value.filter( function(item) {
if(item.title != "undefined")
if(item.title.toLowerCase().includes(args) || item.body.toLowerCase().includes(args))
{
return item;
}
});
return listofItems;
}
我使用了管道,因此它可以用于其他组件,因为我不想在每个必须搜索数据的组件中编写过滤器逻辑。
有人可以建议吗?
答案 0 :(得分:0)
您必须在组件中过滤posts
。这是在一段时间内消除用户输入反跳的好方法,特别是避免在进行api调用时避免多次调用搜索功能。因此,只有在用户中断输入300毫秒时,搜索才会执行。
import { Subject } from 'rxjs';
import {debounceTime} from 'rxjs/operators';
export class MyComponent {
posts: Post[];
result: Post[];
private _searchFilter = '';
private _searchInput$: Subject<string> = new Subject<string>();
get searchFilter(): string {
return this._searchFilter;
}
set searchFilter(value: string) {
this._searchFilter = value;
this._searchInput$.next(this._searchFilter);
}
constructor() {
this._searchInput$.pipe(debounceTime(300))
.subscribe((filter) => this.search(filter));
}
search(filter: string) {
if(filter) {
this.result = posts.filter(p => p.title.includes(filter));
} else {
this.result = posts;
}
}
}
然后在您的模板中:
<input [(ngModel)]="searchFilter">
<span *ngFor ="let data of result" >
{{data.title}}
</span>
Found posts: {{result.length}}