如何使用AJAX实现Angular Material 2自动完成功能

sha*_*mat 2 angular-material2 angular

我在Angular 4项目中使用Angular Material 2 Autocomplete.在此示例中,如何实现自动完成值从HTTP调用加载?

任何人都可以给我一个Plunker演示吗?谢谢

AJT*_*T82 5

首先,你应该展示一些解决问题的尝试,但幸运的是我很无聊并会提供答案;)

在这个示例中,我正在使用:https://jsonplaceholder.typicode.com/users

我们将JSON结果存储为可观察的users.然后我们有我们的可观察量filteredUsers,它将以模板显示.由于这是一个http请求,我们希望使用distinctUntilChangeddebounceTime您选择限制http请求.我们用来捕获值用户的表单控件就是这个例子searchCtrl.在听的时候valueChanges,我们会switchMap用来展平结果.

因此,基于上述注释,您的代码将如下所示:

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
    }))
  )
}
Run Code Online (Sandbox Code Playgroud)

对于模板,我们使用async管道:

<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>
Run Code Online (Sandbox Code Playgroud)

DEMO