如何在Mat-Select中实现搜索功能

时间:2019-05-10 06:46:31

标签: angular

我有一个下拉列表,我希望在其中添加一个搜索选项,当用户添加3个第一个字母时,该选项将在我的情况下搜索行业名称。 这是我的下拉菜单:

 <div class="field-wrapper">
<div class="question-wrapper">
  <h3 class="mat-subheading-1">
    What is the main industry where
    your company is active?
  </h3>
</div>
<div class="field-box">

  <mat-form-field formGroupName="industry">
    <mat-select formControlName="id" placeholder="Industry" (selectionChange)="changed($event)">
      <mat-option>None</mat-option>
      <mat-option *ngFor="let item of industries" [value]="item.id">
        {{item.name}}
      </mat-option>
    </mat-select>

    <div
      *ngIf="industryForm.controls.id.invalid && (industryForm.controls.id.dirty || industryForm.controls.id.touched)"
      class="alert alert-danger">
      <mat-error *ngIf="industryForm.controls.id.errors.required">Must fill this field</mat-error>
    </div>
  </mat-form-field>
</div>

此DropDownlist将显示的值是:

0: "Agriculture and Mining"
1: "Business Services"
2: "Computer and Electronics"
3: "Consumer Services"
4: "Education"
5: "Energy and Utilities"
6: "Financial Services"
7: "Government"
8: "Health, Pharmaceuticals, and Biotech"
9: "Manufacturing"
10: "Media and Entertainment"
11: "Non-profit"
12: "Other"
13: "Real Estate and Construction"
14: "Retail"
15: "Software and Internet"
16: "Telecommunications"
17: "Transportation and Storage"
18: "Travel Recreation and Leisure"
19: "Wholesale and Distribution"

结果:如果用户写(Edu)Education,则将显示。

如果有人有什么想法,请帮忙。

stackblitz here

我想做的是enter link description here,只需做一点编辑,当用户写3封信时就可以进行搜索

1 个答案:

答案 0 :(得分:2)

您可以使用ngx-mat-select-search包来实现相同目的:

首次安装:

npm install ngx-mat-select-search

在app.module.ts中:

import { NgxMatSelectSearchModule } from 'ngx-mat-select-search';

并在导入数组中:

imports: [
   ....,
   NgxMatSelectSearchModule 
]

HTML代码:

<mat-form-field>
    <mat-select [formControl]="control" ngDefaultControl placeholder="Tags" #Select>
        <ngx-mat-select-search [placeholderLabel]="'Search Item'" [noEntriesFoundLabel]="'No matching records found'" [formControl]="control"
         ngDefaultControl></ngx-mat-select-search>
        <mat-option class="m-t" *ngFor="let obj of filteredRecords | async" [value]="obj">
            {{obj}}
        </mat-option>
    </mat-select>
</mat-form-field>

TS代码:

import { takeUntil, take } from 'rxjs/operators';
import { FormGroup, FormControl, Validators } from '@angular/forms'
import { Subject, ReplaySubject } from 'rxjs/Rx';
import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import 'rxjs/add/operator/map';
import { MatSelect } from '@angular/material/select';


@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample implements OnInit {
  items: any[] = [
    "Agriculture and Mining",
    "Business Services"
    , "Computer and Electronics"
    , "Consumer Services"
    , "Education"
    , "Energy and Utilities"
    , "Financial Services"
    , "Government"
    , "Health, Pharmaceuticals, and Biotech"
  ];


  /** control for the selected bank for multi-selection */
  public control: FormControl = new FormControl();

  private _onDestroy = new Subject<void>();
  public filteredRecords: ReplaySubject<any[]> = new ReplaySubject<any[]>(1);

  @ViewChild('Select') select: MatSelect;

  ngOnInit() {
    this.setInitialValue();
    // set initial selection
    this.control.setValue([]);
    // load the initial bank list
    this.filteredRecords.next(this.items.slice());

    this.control.valueChanges
      .pipe(takeUntil(this._onDestroy))
      .subscribe(() => {
        this.filterBanksMulti();
      });
  }

  private setInitialValue() {
    this.filteredRecords
      .pipe(take(1), takeUntil(this._onDestroy))
      .subscribe(() => {
        this.select.compareWith = (a: any, b: any) => a === b;
      });
  }

  private filterBanksMulti() {
    if (!this.items) {
      return;
    }
    // get the search keyword
    let search = this.control.value;
    if (!search) {
      this.filteredRecords.next(this.items.slice());
      return;
    } else {
      search = search.toLowerCase();
    }
    if (search.length >= 3) {
    // filter the banks
     this.filteredRecords.next(
      this.items.filter(item => item.toLowerCase().indexOf(search) > -1)
     );
    }
  }
}

Working_Demo