我在INTERNET上搜索了很多但仍无法弄清楚如何在没有任何第三方的情况下制作自定义自动建议器。经过很多谷歌我发现this
但问题是我对api的回答有点不同我得到了回复:
[{"id":"1","name":"aa"},{"id":"2","name":"bb"}...]
因为我将[object] [object]作为管道中的值。
任何人都可以帮助我如何使用此管道处理此请求。我希望他们应该是一个文本框,其上应该有列表和用户输入,以下建议可能会有所不同。
管:
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数组是不同的,如上所述。
答案 0 :(得分:0)
鉴于数据源是一个对象数组,为了动态,我将使用以下管道来迭代每个对象的值,然后如果找到匹配将保持对象显示:
<强>管强>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(items: Array<any>, filter: string): any {
if (!filter) {
return items;
}
return items.filter(item => {
for (let field in item) {
if (item[field] === null || item[field] === undefined){
continue;
}
if (item[field].toString().toLowerCase().indexOf(filter.toLowerCase()) !== -1) {
return true;
}
}
return false;
}
);
}
}
HTML
<input type="text" [(ngModel)]="search" placeholder="Filter...">
<div *ngFor="let item of datasource | filter:search"></div>
查看管道的pure: false
声明。这告诉管道连续过滤数据,因此如果您有一个动态将数据推送到数据源的服务,过滤后的显示将自动更新。同样使用这样的管道,您可以过滤对象的所有值,对象可以动态更改结构而不会影响过滤器。
答案 1 :(得分:0)
您可以尝试类似下面的内容
<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;
}
}
您可以根据需要更新管道。