繁体   English   中英

Angular 材料自动完成无法正常工作

[英]Angular material autocomplete doesn't work properly

我正在使用 Angular 材料自动完成来自动完成用户的搜索关键字超过我的数据库中 250 万个现有单词,我还将搜索 function 限制为仅显示自动完成的结果,直到第 4 个字符,尽管我的页面在第一个字符之后被阻止用户键入的字符对我来说似乎不合逻辑(如果在用户键入第 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() function 的 arguments 以显示您想要的建议数量)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM