angular - 如何使用 AJAX 实现 Angular Material 2 自动完成

标签 angular angular-material2

我在我的 Angular 4 项目中使用 Angular Material 2 Autocomplete。在这个 example 中,我如何实现自动完成值从 HTTP 调用加载? ?

谁能给我一个 Plunker 演示?谢谢

最佳答案

首先,您应该尝试解决您的问题,但幸运的是我很无聊,会提供答案;)

在此示例中,我使用的是:https://jsonplaceholder.typicode.com/users

我们将该 JSON 结果存储为 users 中的可观察对象。然后我们有了可观察的 filteredUsers ,它将显示在模板中。由于这是一个 http 请求,我们希望使用您选择的 distinctUntilChangeddebounceTime 来限制 http 请求。在本例中,我们用来捕获用户输入值的表单控件是 searchCtrl。在监听 valueChanges 时,我们使用 switchMap 来展平结果。

因此,根据以上评论,您的代码将如下所示:

更新(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
    }))
  )
}

对于模板,我们使用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>

DEMO


旧:

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

关于angular - 如何使用 AJAX 实现 Angular Material 2 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47088363/

相关文章:

Angular 2 - 将构造函数中的依赖注入(inject)与其他参数混合

angular - 在 Angular Material Design 中的 aria-label 内平移管道失败

validation - Angular2/ Material 2 : md-input-container label is not resetting float when value is changed programmatically

angular - 如何从 angular-material2 对话框与其父级进行通信

angular - 如果 FormGroup 通过 valueChanges 相互监听,则 Angular 中的 FormGroup 无法正确看到其子项的单个更改

Angular 2 - 无法绑定(bind)到 'settings',因为它不是 'my-datatable' 的已知属性

angular - 获取 FormGroup/FormControl 中的验证器

Angular Material datepicker 将时间戳设置为表单控件值

php - Laravel $request->all() 使用 multipart/form-data 为空

angular - 理解 *ngIf 表达式