[英]custom filter search in angular 5
data : [
{
id :1,
name : "client A",
industry: "Industry 1",
img:"https://abc"
},
{
id :2,
name : "client Ab",
industry: "Industry 2",
img:"https://abc"
},
{
id :3,
name : "client megha",
industry: "Industry 5",
img:"https://abc"
},
{
id :4,
name : "shubham",
industry: "Industry 1",
img:"https://abc"
},
{
id :4,
name : "rick",
industry: "Industry 1",
img:"https://abc"
}
]
我希望过滤器执行以下操作:
当我开始写单词“ c”时,我希望rick消失,现在默认行为是,所有内容仍然显示(c在rick的中间)。
严格模式是我不想使用的东西,我想要的行为是:
如果输入中没有任何值,那么我想查看全部内容,如果我开始写,则希望通过firstName查看确切的值。 如果我写“ m”,则不应显示任何内容,因为名称均不以m开头。 我想根据名称和行业进行搜索,但不希望基于img进行搜索。 请帮忙。
当您使用Typescript和angular 5时,因此可以使用ES6方法,该方法可用于名为startsWith
字符串,该字符串仅在起始索引处存在该值时才返回true。
您可以使用startsWith
方法创建一个带有角度的自定义管道,以根据您在文本框中键入的内容过滤掉数据。 例如,如果您r
则它将仅返回rick
。 对于此示例,我遵循不区分大小写的搜索。 检查下面的代码
自定义管道startWith
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'startsWith'})
export class startsWithPipe implements PipeTransform {
transform(value: any[], term: string): any[] {
return value.filter((x:any) => x.name.toLowerCase().startsWith(term.toLowerCase()))
}
}
ngModel在app.component中的用法
app.component.ts
import { Component } from '@angular/core';
import {startsWithPipe} from './customstart.pipes';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 5';
query:string = '';
data = [
{
id :1,
name : "client A",
industry: "Industry 1"
},
{
id :2,
name : "client Ab",
industry: "Industry 2"
},
{
id :3,
name : "client megha",
industry: "Industry 5"
},
{
id :4,
name : "shubham",
industry: "Industry 1"
},
{
id :4,
name : "rick",
industry: "Industry 1"
}
]
}
app.component.html
<input type="text" [(ngModel)]="query">
<ul>
<li *ngFor="let item of data | startsWith : query">{{item.name}}</li>
</ul>
这是一个工作示例: https : //stackblitz.com/edit/angular-custom-pipes-mkah47
编辑:要显示结果,如果名字的开头字符或行业的开头字符与键入的字符匹配,则需要如下所示更改管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'startsWith'})
export class startsWithPipe implements PipeTransform {
transform(value: any[], term: string): any[] {
return value.filter((x:any) => x.name.toLowerCase().startsWith(term.toLowerCase()) || x.industry.toLowerCase().startsWith(term.toLowerCase()))
}
}
这是要测试的样本数据
data = [
{
id :1,
name : "client A",
industry: "Tech"
},
{
id :2,
name : "client Ab",
industry: "Tourism"
},
{
id :3,
name : "client megha",
industry: "Hotel"
},
{
id :4,
name : "shubham",
industry: "Retail"
},
{
id :4,
name : "rick",
industry: "IT"
}
]
我在这里更新了示例: https : //stackblitz.com/edit/angular-custom-pipes-mkah47
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.