angularrxjsmat-autocomplete

Angular async autocomplete filtering without http request?


I'm trying to create a users async autocomplete as following:

this.users = this.usersService.getUsers()
<input type="text" matInput formControlName="user" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let user of users | async" [value]="user.id">
        {{ user.name }}
    </mat-option>
</mat-autocomplete>

I'm trying to filter the autocomplete options on typing, but I can't find how.

this.user.valueChanges.subscribe((x) => {
  // Filter users
});

Is it possible to filter users without making another http request?


Solution

  • Yeah you can use rxjs filter for that. I would create a separate state variable that filters the users list.

    this.filtered$ = this.user.valueChanges.pipe(
      filter(input => !!input),
      map(input => input.toLowerCase()),
      switchMap(input => this.users.pipe(
        map(users => users.filter(user => user.name.toLowerCase().includes(input)))
      ))
    )
    

    And then use the filtered$ in the template as options:

    <mat-option *ngFor="let user of filtered$ | async" [value]="user.id">
           {{ user.name }}
    </mat-option>