如何使用 AJAX 实现 Angular Material 2 自动完成 [英] How to implement Angular Material 2 Autocomplete with AJAX

查看:26
本文介绍了如何使用 AJAX 实现 Angular Material 2 自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

Can anyone give me a Plunker demo? Thank you

推荐答案

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

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

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

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

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:

更新 (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 管道:

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>

演示

旧:

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
    }));
}

演示

这篇关于如何使用 AJAX 实现 Angular Material 2 自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆