簡體   English   中英

為什么 mat-autocomplete 不顯示搜索到的選項?

[英]Why is the mat-autocomplete not displaying the searched options?

這是我正在使用的表格:

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

您應該將 Observable 的字符串數組分配給this.result 但是您分配的是普通字符串數組。 async pipe 適用於 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;
}

工作堆棧閃電戰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM