我正在使用Angular Materials自动完成功能来自动完成数据库中超过250万个现有单词的用户搜索关键字,我还限制了搜索功能,仅在第4个字符之前显示自动完成的结果,尽管我的页面在第一个字符后被阻止用户输入的字符对我来说似乎不合逻辑(如果这是大数据问题,应该在用户键入第四个字符后出现),这是我的Typescript代码:
control = new FormControl();
filteredWords: Observable<string[]>;
url = "./assets/existingwords.txt";
public words : string[] =[];
private _filter(value: string): string[] {
const filterValue = value.toLowerCase().replace(/\s/g, '');
return this.words.filter(word => word.toLowerCase().replace(/\s/g, '').includes(filterValue));
}
ngOnInit() : void {
this.filteredWords = this.control.valueChanges.pipe(
startWith(''),
map(value => value.length>=4 ? this._filter(value): this.words.slice())
);
}
这是我的HTML代码:
<div class="form-group">
<input matInput type="text" class="form-control" id="idWord" [formControl]="control" [(ngModel)]="myword" placeholder="Saisir votre terme ici.." name="myword" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let word of filteredWords | async" [value]="word">
{{word}}
</mat-option>
</mat-autocomplete>
</div>
那么问题出在我的lambda表达式中的else条件,正是这部分代码:
this.words.slice()
总是返回我所有的数据条目,当用户键入少于4个字符时,这会导致材料自动完成块,否则解决方案是将其更改为:
this.words.slice(0,0)
这意味着,如果用户键入的字符少于4个,我们将不会为他显示任何建议(您可以修改slice()函数的参数以显示所需的建议数量)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句