仅当输入的字符超过 2 个时,才会触发材质自动完成



我有一个材质自动完成组件,运行良好。我无耻地从各种在线示例中将其拼凑在一起。我正在努力弄清楚如何在输入 2 个或更多字符时仅触发搜索。

assignSearchAutocomplete(){
this.acCtrl.valueChanges
.pipe(
debounceTime(500),
tap(() => {
this.acErrorMsg = "";
this.acFilteredItems = [];
this.acIsLoading = true;
}),
switchMap(value => this.svcGetFacetGql.watch({ name: ".*" + value + ".*", label: this.facetLabel, options: { fetchPolicy: 'cache-and-network' } })
.valueChanges
.pipe(
tap(() => {
this.acIsLoading = false
}),
)
)
)
.subscribe(response => {
if (response['data'] == undefined) {
this.acErrorMsg = response['Error'];
this.acFilteredItems = [];
} else {
this.acErrorMsg = "";
this.acFilteredItems = response['data']['Facet'];
}
});
}

我尝试插入 if 语句并使用三元运算符:? 但无法让它工作。

谢谢

您可以筛选出字符串为空或太短的值。

assignSearchAutocomplete(){
this.acCtrl.valueChanges
.pipe(
// new part
filter(value => value && value.length >=2),
// end of new part
debounceTime(500),
tap(() => {
this.acErrorMsg = "";
this.acFilteredItems = [];
this.acIsLoading = true;
}),
// ...
)
.subscribe(response => {
if (response['data'] == undefined) {
this.acErrorMsg = response['Error'];
this.acFilteredItems = [];
} else {
this.acErrorMsg = "";
this.acFilteredItems = response['data']['Facet'];
}
});
}

如果你尝试使用filter怎么办?

this.acCtrl.valueChanges
.pipe(
debounceTime(500),
filter(value => value.length > 2),
tap(() => {
...
}
);

相关内容

最新更新