How to implement Angular Material 2 Autocomplete with AJAX

痴心易碎 提交于 2019-12-22 18:24:50

问题


I am using Angular Material 2 Autocomplete in my Angular 4 project. How can I implement such that the autocomplete values are loading from an HTTP call, in this example?

Can anyone give me a Plunker demo? Thank you


回答1:


First of all, you should please show some attempt to solve your issue, but luckily I'm bored and will provide an answer ;)

Here in this sample I'm using: https://jsonplaceholder.typicode.com/users

we store that JSON result as an observable in users. Then we have our observable filteredUsers which will be shown in template. Since this is a http-request, we would want to use distinctUntilChanged and debounceTime of your choosing, to restrict the http-requests. The formcontrol we are using to capture the value user is typing is in this example searchCtrl. When listening to valueChanges, we use switchMap to flatten the result.

So based on the above comments, your code would look like the following:

UPDATE (rxjs 6)

this.filteredUsers = this.searchCtrl.valueChanges.pipe(
  startWith(null),
  debounceTime(200),
  distinctUntilChanged(),
  switchMap(val => {
    return this.filter(val || '')
  })
 )
}

filter(val: string) {
  return this.users.pipe(
    map(response => response.filter(option => {
      return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
    }))
  )
}

and for the template, we use the async pipe:

<mat-form-field>
  <input matInput [matAutocomplete]="auto" [formControl]="searchCtrl">
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let user of filteredUsers | async" 
      [value]="user.name">
      <span>{{ user.name }}</span>
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

DEMO


OLD:

this.filteredUsers = this.searchCtrl.valueChanges
  .startWith(null)
  .debounceTime(200)
  .distinctUntilChanged()
  .switchMap(val => {
    return this.filter(val || '')
})      

filter(val: string) {
  return this.users
    .map(response => response.filter(option => { 
      return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
    }));
}

DEMO



来源:https://stackoverflow.com/questions/47088363/how-to-implement-angular-material-2-autocomplete-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!