Angular mat-autocomplete 显示错误的过滤选项

问题描述

当我在 input 中输入内容时,我必须找到包含该子字符串的所有选项。问题是过滤后的值显示不正确。

例如,我有几个词:n、new、need、sNow

  1. 当我输入“n”时,自动完成不显示任何内容(但应显示所有选项)。
  2. 当我输入“ne”时,它显示n,new,need,sNow(但应该显示new,need)。
  3. 当我输入“new”时,它显示new,need(但应该只显示new)。 就像搜索服务采用先前输入的值一样。

我的模板:

<form [formGroup]="myForm">
<input [formControl]="myForm.get('myInput')" type="text" [matAutocomplete]="myAutocomplete"/>
<mat-autocomplete #myAutocomplete="matAutocomplete">
    <mat-option *ngFor="let item of autocompleteItems" [value]="item">
        {{item}}
    </mat-option>
</mat-autocomplete>
</form>

在我的组件中:

public myForm = new FormGroup({myInput: new FormControl('',[Validators.required])});
public autocompleteItems: string[] = [];

ngOnInit() {
  this.myForm.get('myInput').valueChanges
    .pipe(
        takeuntil(this.unsubscribe),switchMap((inputString: string) => this.mySearchService.search(inputString)))
    .subscribe((foundStrings: string[]) => {
        this.autocompleteItems = foundStrings;
        console.log(this.autocompleteItems);
    });
}

P。 S. 日志显示正确的字符串数组:

  1. 输入 n - n、new、need、sNow
  2. 输入ne - 新的,需要
  3. 输入 new - new

请告诉我我做错了什么。

解决方法

管道 pairwise 到您的 valueChanges Observable 以获取订阅中的 previous/next 值,然后使用 next 作为 currentValue

public myForm = new FormGroup({
  myInput: new FormControl('',[Validators.required])
});
public autocompleteItems: string[] = [];

ngOnInit() {
  this.myForm.get('myInput').valueChanges
    .pipe(pairwise())
    .pipe(
      takeUntil(this.unsubscribe),switchMap((inputString: string) => this.mySearchService.search(inputString)))
    .subscribe(([prev,next]: [any,any]) => {
      this.autocompleteItems = next;
      console.log(this.autocompleteItems);
    });
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...