【发布时间】:2020-02-19 05:30:45
【问题描述】:
我想知道如何使用异步管道使用多个对象属性过滤搜索结果。目前,我可以根据 name 属性进行过滤并显示过滤后的结果,但我也希望能够在 username 属性上进行搜索。这是我到目前为止所拥有的: 在我的 TS 文件中:
public formSetup = this.fb.group({
formSearch: new FormControl('')
})
constructor(private service: Service,
private fb: FormBuilder) { }
ngOnInit(): void {
this.getFilters();
}
public getFilters() {
const filter = (val: string): Observable<Array<object>> => {
return this.service.getItems()
.pipe(
map(response => response.filter(option => {
const value = `${option.name}`
return value.toLowerCase().indexOf(val.toLowerCase()) === 0;
}))
);
}
this.filteredItems = this.formSetup.get('formSearch').valueChanges
.pipe(
startWith(null),
debounceTime(200),
distinctUntilChanged(),
switchMap(val => {
return filter(val || '');
})
);
}
在我的 HTML 文件中:
<input type="text" formControlName="formSearch">
</div>
<search [items]="filteredItems"></search>
最后,在我显示结果的组件中:
<search-card *ngFor="let item of (items | async ); trackBy:trackingFn" [items]="item"></search-card>
【问题讨论】: