[英]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.