Angular Material Autocomplete to display Employee Name from RestApi

Viewed 101

I am looking to use Angular Material Autocomplete to display only Employee name from the Rest API that is returning array of data as below:

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

Defined the model as below:

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

I am using below subscribe method to get the data

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

Below is the code for Filtering:

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

But nothing seems to be working in the input search(autocomplete). Please advise.

1 Answers

send filter to the server for filtering by writing input word.

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

show autocomplate as below

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

we use displayFn to show employeeName in select input after selecting

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