Reputation: 4429
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?
Upvotes: 7
Views: 8282
Reputation: 73337
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
Upvotes: 9
Reputation: 1456
Most likely you have forgotten to parse the result that you are getting from server.
this.states = JSON.parse(res);
This should fix the issue.
Upvotes: 1