Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Material 2 (Angular 4) autocomplete to searching an external API

I'm trying to get Angular Material 2 autocomplete to work search an API instead of search inside an array as per example. This is what I tried:

HTML:

<mat-form-field fxFlex="33" class="mr-20 mt-20">
  <input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
      <span>{{ state.name }}</span>
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

TS:

this.stateCtrl = new FormControl();
this.filteredStates = this.stateCtrl.valueChanges
  .startWith(null)
  .debounceTime(400)
  .do(value => {
    this.ClientsService.search(value).then( res => {
      console.log(res, 'oi');
      this.states = res;
    })
  });

However, when I type, I get this error: Error: Cannot find a differ supporting object 'e' of type 'string'. NgFor only supports binding to Iterables such as Arrays.

Note that e is what I type in the search field. The response I'm getting from the server is an array with objects in it.

What am I missing here?

like image 949
WagnerMatosUK Avatar asked Oct 22 '17 07:10

WagnerMatosUK


1 Answers

If it is states that you want to show in your template, as per what you are storing your incoming data to, then that is what you want to show in template.

So do:

<mat-option *ngFor="let state of states" [value]="state.name">

instead of

<mat-option *ngFor="let state of filteredStates | async" [value]="state.name">

with TS:

this.filteredStates = this.stateCtrl.valueChanges
  .startWith(null)
  .debounceTime(400)
  .do(value => {
    this.ClientsService.search(value).then( res => {
      console.log(res, 'oi');
      this.states = res;
    })
  })
  .subscribe()

Plunker with random Chuck Norris jokes ;) https://stackblitz.com/edit/angular-uu4cya?file=app%2Fapp.component.ts

like image 145
AT82 Avatar answered Oct 08 '22 11:10

AT82