首页 > 解决方案 > Angular Material Autocomplete 以显示来自 RestApi 的员工姓名

问题描述

我希望使用 Angular Material Autocomplete 仅显示来自 Rest API 的员工姓名,该 API 返回数据数组,如下所示:

{
         "employees": [
           {
             "employeeID":"5657",
             "employeeName":"James Carter",
             "employeeDept": ["Dept1", "Dept2", "Dept3"]               
           },
           {
             "employeeID":"5868",
             "employeeName":"Helen Burt",
             "employeeDept": ["Dept5", "Dept2", "Dept6"]               
           }
         ]
       }

定义模型如下:

interface Employee {
employeeID: number
empoyeeName: string
employeeDept: string[]
}

我正在使用以下订阅方法来获取数据

this.getAPI.getEmployees()
    .pipe(pluck('employees'))
    .subscribe(e => {
      this.employees = e;
    });

下面是过滤的代码:

this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value))
    );

private _filter(value: string): EmployeesList[] {
    const filterValue = value.toLowerCase();

    return this.employees.filter(option => option.employeeName.toLowerCase().indexOf(filterValue) === 0); 
  }

但在输入搜索(自动完成)中似乎没有任何工作。请指教。

标签: angularangular-material

解决方案


通过写入输入词将过滤器发送到服务器进行过滤。

this.myControl.valueChanges.pipe(
        startWith(""),
        debounceTime(300),
        filter((f) => typeof f == typeof ""),
        tap(() => (this.isLoading= true)),
        switchMap((value) =>
         this.getAPI.getEmployees({
filter:value
}).pipe(finalize(() => (this.isLoading= false)))
        )
      )
      .subscribe((result) => {
        this.employees = result;
      });

显示自动编译如下

  <mat-form-field class="full-width" (click)="clickBox()">
    <mat-label>Employee</mat-label>
    <input matInput [matAutocomplete]="auto" [formControl]="myControl">
  </mat-form-field>
  <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
    <mat-option *ngIf="isLoading"  class="is-loading">
      <mat-spinner diameter="50"></mat-spinner>
    </mat-option>
    <ng-container *ngIf="!isLoading">
      <mat-option *ngFor="let employee of employees" [value]="employee">
        <span>{{ employee.employeeName }}</span>
      </mat-option>
    </ng-container>
  </mat-autocomplete>

选择后我们使用 displayFn 在选择输入中显示员工姓名

  displayFn(employee: Employee) {
    if (employee) {
      return employee.employeeName;
    }
  }

推荐阅读