【问题标题】:Why is the mat-autocomplete not displaying the searched options?为什么 mat-autocomplete 不显示搜索到的选项?
【发布时间】:2020-08-04 22:54:22
【问题描述】:

这是我正在使用的表格:

<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;
}

【问题讨论】:

  • 你的方法this.find是做什么的?发布您的代码
  • this.result 应该包含匹配字符串的数组。 this.result 在您共享的代码中包含什么内容?
  • @Shank 更新了代码

标签: angular autocomplete angular-material angular10


【解决方案1】:

您应该将字符串数组的 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>

Typescript 更改

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;
}

工作stackblitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-07
    • 2020-10-15
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2019-08-16
    相关资源
    最近更新 更多