角度搜索过滤器(由字符串数组组成)

时间:2020-05-22 14:53:03

标签: angular typescript

html:

<input matInput placeholder="Search" value="" formControlName="searchbar">

ts:

typesOfShoes: string[] = ['Boots', 'Clogs', 'Loafers', 'Moccasins', 'Sneakers'];

我需要显示与数组数据匹配的数据。

2 个答案:

答案 0 :(得分:0)

string [] = ['Boots','Clogs','Loafers','Moccasins','Sneakers'];

让searchKey;(必须输入的值)

让Search = string.find((a)=> a.includes(searchKey);

您会在serch变量中获得匹配值

答案 1 :(得分:0)

HTML

<mat-form-field>
   <input matInput [matAutocomplete]="autoComplete"
      placeholder="Search" [formControl]="searchControl">
   <mat-autocomplete #autoComplete>
      <mat-option *ngFor="let shoe of filteredShoes" [value]="shoe"> {{shoe}} </mat-option>
   </mat-autocomplete>
</mat-form-field>

TS

  searchControl = new FormControl();
  typesOfShoes: string[] = ['Boots', 'Clogs', 'Loafers', 'Moccasins', 'Sneakers'];
  filteredShoes: string[];

  ngOnInit() {
     this.searchControl.valueChanges.subscribe(searchSrting => {
        this.filteredShoes = this.getSearchResult(searchSrting).slice();
  });

  getSearchResult(searchString: string): string[] {
     return this.typesOfShoes.filter(x => x.toLowerCase().includes(searchString.toLowerCase()))
  }