Angular2 自动建议器 [英] Angular2 Auto suggester
问题描述
我在 INTERNET 上搜索了很多,但仍然无法弄清楚如何在没有任何第三方的情况下制作自定义自动建议.经过大量的谷歌我发现 this
I have been searching a lot on INTERNET but still unable to figure out how i can make custom auto suggester without any third party. After a lot of google I found this
但问题是我对 api 的响应有点不同,我得到的响应是:
but the issue is that my response from api is a bit different i am getting response as :
[{"id":"1","name":"aa"},{"id":"2","name":"bb"}...]
因此,我将 [object][object] 作为管道中的值.
due to which i am getting [object][object] as value in pipe.
任何人都可以帮助我如何用这个管道处理这个请求.我希望它们应该是一个文本框,点击后应该会出现列表,并且在用户输入时,以下建议可能会有所不同.
Can anyone please help how i can handle this request with this pipe. I want that their should be a text box on whose click there should be listing and on user input the below suggestions may vary.
管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
transform(value: any, input: string) {
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any) {
return el.toLowerCase().indexOf(input) > -1;
})
}
return value;
}
}
在 ts:
import { Component } from '@angular/core';
import {FilterPipe} from './pipes'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title:String;
names:any;
constructor(){
this.title = "Angular 2 simple search";
this.names = ['Prashobh','Abraham','Anil','Sam','Natasha','Marry','Zian','karan']
}
}
*** 这很完美,但在我的情况下,this.name 数组如上所述.
*** this works perfectly but in my case this.name array is deferent as told above.
推荐答案
你可以尝试类似下面的方法
You can try something similar like below
<input type="text" [(ngModel)]="queryString" id="search" placeholder="Search to type">
<ul>
<li *ngFor="let n of list | FilterPipe: queryString : searchableList ">
{{n.name}} ({{n.id}})
</li>
</ul>
传递要搜索的必填字段
this.searchableList = ['name','id']
管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
transform(value: any, input: string,searchableList : any) {
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any) {
var isTrue = false;
for(var k in searchableList ){
if(el[searchableList[k]].toLowerCase().indexOf(input) > -1){
isTrue = true;
}
if(isTrue){
return el
}
}
})
}
return value;
}
}
您可以根据需要更新管道.
You can update the pipe according to your needs.
这篇关于Angular2 自动建议器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!