我正在尝试创建自动完成功能,但还不知道如何操作。我有一个本地 json 文件,其中包含一个我应该搜索的数组。我列出了其中的所有数据,但现在我不知道该怎么做。这是我尝试过的:
private _url = 'assets/json-data/restaurants.json';
constructor(private _http: Http) {}
getRestaurants () {
return this._http.get(this._url)
.map((response: Response) => response.json());
}
这是我的 app.component.ts:
restaurants: any[] = [];
filteredRestaurants: any[] = [];
searchValue: string;
constructor(private restaurantsService: RestaurantsService){}
ngOnInit() {
}
search() {
this.restaurantsService.getRestaurants()
.subscribe(
(response) => {
this.restaurants = response.results;
for (const r of this.restaurants) {
if (r.name.indexOf(this.searchValue) > 0) {
this.filteredRestaurants = response.results;
} else {
this.filteredRestaurants = [];
}
}
// this.restaurants = response.results;
},
(error) => {
console.log(error);
}
);
}
在我的 html 中,我输入:
<div class="search-input-box">
<input type="text" [(ngModel)]="searchValue" (keyup)="search()" class="search-input">
<div *ngIf="filteredRestaurants && filteredRestaurants.length > 0" class="ac-list">
<ul *ngFor="let r of filteredRestaurants">
<li>{{ r.name }}, {{ r.address.city }}</li>
</ul>
</div>
</div>
我想我不能这样做是因为我在后端没有实际的 searchValue
吗?我怎么能只用这个 json 文件呢?
编辑:我编辑了我的问题,这是我尝试过的,但它并没有像我想要的那样工作。我尝试遍历数组中的每个对象作为响应并查看值是否正确
编辑 2:用这个管道解决了它:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'restaurant' })
export class SearchPipe implements PipeTransform {
transform(restaurants: any, searchValue: any): any {
if(searchValue == null) return restaurants;
return restaurants.filter(function(restaurant){
return restaurant.name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
})
}
}
最佳答案
我相信您所追求的是通常被称为“Typeahead”的东西 - 您在搜索框中输入内容,然后使用您输入的内容与 JSON 数组中的项目之间的相似性,搜索框会尝试“建议”您正在输入的内容。
我建议使用来自 ngx-bootstrap 的预制 Angular 组件库.该库中有一个 Typeahead 组件。
我在我的大多数 Angular 项目中都使用这个库 - 关于 Typeahead 组件的文档应该足够详细以帮助你。
关于angular - 如何创建自动完成 - Angular 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48775283/