角材料不过滤选项

时间:2021-07-09 20:02:32

标签: javascript angular typescript

我正在研究自动完成,它不是过滤选项。问题出在 _filter() 中。当 _filter() 修改为

时一切正常
return this.names.filter(option => option.toLowerCase().includes(filterValue));

但我想知道为什么它不适用于下面的代码片段。

这是我试过的

template.html

<label>Search names</label>
<input type="text"
       placeholder="search name"
       aria-label="Number"
       matInput
       [formControl]="myControl"
       [matAutocomplete]="auto">
     
<mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
      {{option}}
    </mat-option>
</mat-autocomplete>

template.ts

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'app-matautocom',
  templateUrl: './matautocom.component.html',
  styleUrls: ['./matautocom.component.css']
})
export class MatautocomComponent implements OnInit {

  names: string[] = ['ghui', 'ustu', 'caty','momo', 'rekh', 'john', 'kemp'];
  myControl: FormControl = new FormControl();
  filteredOptions: Observable<string[]> | undefined;
  constructor() { }

  ngOnInit(): void {
    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value))
    );
  }
  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
 
     return this.names.filter((option) =>  {
       console.log(filterValue)
      option.toLowerCase().includes(filterValue);
      return option;
    })   
   
  }

}


1 个答案:

答案 0 :(得分:1)

问题是您从提供给 filter

的函数返回的值
option.toLowerCase().includes(filterValue) // returns a boolean that works with filter
// thats why this works
// return this.names.filter(option => option.toLowerCase().includes(filterValue));

在您的另一个示例中,您返回的选项变量不是布尔值:

return this.names.filter((option) =>  {
      console.log(filterValue)
      // the result of includes is lost
      option.toLowerCase().includes(filterValue);
     // this is actually returning the option, not a boolean expected by filter
      return option;

      // To fix this, just return the result of includes
      // return option.toLowerCase().includes(filterValue);
    })