0

这是我正在使用的表格:

<form [formGroup]="searchForm" id="searchForm">
   <mat-form-field>
      <input
      matInput
      type="text"
      name="awesome"
      id="awesome"
      [formControl] = "formCtrl"
      [matAutocomplete] = "auto"
      value="{{ awesomeText }}"
      [matAutocomplete]="auto">
      <mat-autocomplete #auto = "matAutocomplete">
         <mat-option *ngFor = "let res of result | async" [value] = "res">
         {{res}}
         </mat-option>
      </mat-autocomplete>
   </mat-form-field>
</form>

这是里面constructor()

this.formCtrl = new FormControl();
this.formCtrl.valueChanges.subscribe((newValue) => {
    this.result = this.find(newValue);
    console.log('yes');
});

正在打印,yes所以我知道这是有效的,但mat-autocomplete没有显示任何内容。该result变量也在更新,因为我可以看到它在控制台上打印。我无法理解为什么没有显示搜索到的值。

我将不胜感激任何帮助!

编辑

这是find()方法:

find(val: string): string[] {
    const matchFound = [];

    for (let i = 0; i < dataJson.length; i++) {
        if (dataJson[i].text.toLowerCase().startsWith(val) || dataJson[i].text.startsWith(val)) {
            matchFound.push(dataJson[i].text);
        }
    }

    console.log('matches ' + matchFound);
    return matchFound;
}
4

1 回答 1

0

您应该将字符串数组的 Observable 分配给this.result. 但是您正在分配普通的字符串数组。async管道适用于 observable 而不是普通数组。在模板中,您需要在下面进行更改

<mat-option *ngFor="let res of result | async" [value]="res">{{res}}</mat-option>

<mat-option *ngFor="let res of result | async" [value]="res.text">{{res.text}}</mat-option>

打字稿更改

ngOnInit() {
  this.result = this.myControl.valueChanges.pipe(
    startWith(""),
    map(value => this.find(value))
  );
}

find(val: string): {
  id: number,
  text: string
}[] {
  const matchFound: {
    id: number,
    text: string
  }[] = [];

  for (let i = 0; i < this.dataJson.length; i++) {
    if (
      this.dataJson[i].text.toLowerCase().startsWith(val) ||
      this.dataJson[i].text.startsWith(val)
    ) {
      matchFound.push(this.dataJson[i]);
    }
  }

  console.log("matches " + matchFound);
  return matchFound;
}

工作堆栈闪电战

于 2020-08-04T14:54:22.367 回答