如何使用AJAX实现Angular Material 2自动完成 [英] How to implement Angular Material 2 Autocomplete with AJAX
问题描述
我在Angular 4项目中使用Angular Material 2自动完成功能.在此
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
中的可观察值.然后,我们有可观察的filteredUsers
,它将显示在模板中.由于这是一个http请求,因此我们希望使用您选择的distinctUntilChanged
和debounceTime
来限制http请求.在此示例中,我们用来捕获用户键入的值的formcontrol是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>
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
这篇关于如何使用AJAX实现Angular Material 2自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!