angular - Angular 7:使用异步管道过滤多个键的搜索结果
问题描述
我想知道如何使用异步管道使用多个对象属性过滤搜索结果。目前,我可以根据 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>
解决方案
您可以修改该filter()
方法以也搜索username
属性。
return this.service.getItems()
.pipe(
map(response => response.filter(option => {
const value = `${option.name}`;
const username = `${option.username}`;
return value.toLowerCase().indexOf(val.toLowerCase()) === 0 ||
username.toLowerCase().indexOf(val.toLowerCase()) === 0;
}))
);
推荐阅读
- javascript - Firefox 多次点击后不显示表单的错误信息
- javascript - 如何更改 JS dom 中变量的颜色?
- android - MPAndroidChart - 单击图表上的条目会突出显示错误的条目。有没有在本地重写lib的解决方案?
- javascript - Javascript(反应)计算器取决于值之间
- highcharts - Scatter Highcharts 响应问题 Yii2
- ruby - Ruby 中二维数组的紧凑型
- css - 我无法覆盖特定性来更改导航栏中 el 的颜色
- c++ - 用于打印结构成员的 printf 中的总线错误
- python - 如何在 Python 中使用 sqlite3 删除前“n”行
- regex - 如何使用正则表达式来验证类似于此概述结构的输入字符串?