前言
我们在开发过程中经常会遇到在页面上实现全局搜索的需求, 例如: 表格搜索, 通过关键词检索整个表格, 过滤出我们需要的数据. 在 Angular6 中我们可以通过 Filter + Pipe 的方式来实现这个功能. 下面我们看一下实现代码.
实现代码
第一步
新建一个名为 filter.pipe.ts 的文件, 这部分是实现的核心代码:
- import { Pipe, PipeTransform } from '@angular/core';
- @Pipe({ name: 'globalFilter'})export class GlobalFilterPipe implements PipeTransform { transform(items: any, filter: any, defaultFilter: boolean): any { if (!filter){ return items; }
- if (!Array.isArray(items)){ return items; }
- if (filter && Array.isArray(items)) { let filterKeys = Object.keys(filter);
if (defaultFilter) { return items.filter(item => filterKeys.reduce((x, keyName) => (x && new RegExp(filter[keyName], 'gmi').test(item[keyName])) || filter[keyName] == "", true)); } else { return items.filter(item => { return filterKeys.some((keyName) => { return new RegExp(filter[keyName],'gmi').test(item[keyName]) || filter[keyName] ==""; }); }); } } }}
代码部分的正则表达式可以根据需要替换, 这里是全局匹配.
第二步
在 App.module.ts 文件中导入.
- import {
- AppRoutingModule
- } from './/app-routing.module';import {
- DashbordComponent
- } from './dashbord/components/dashbord.component';import {
- LeftNavComponent
- } from './shared/left-nav/components/left-nav.component';import {
- GlobalFilterPipe
- } from './shared/filter.pipe'
- registerLocaleData(zh);
- @NgModule({
- declarations: [ CategoryComponent, LayoutComponent, DashbordComponent, LeftNavComponent, GlobalFilterPipe ], imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, HttpClientModule, NgZorroAntdModule, AppRoutingModule ], providers: [{
- provide: NZ_I18N, useValue: zh_CN
- }], Bootstrap: [LayoutComponent]
- })export class AppModule {
- }
第三步
在需要的 html 文件中应用, 在 componet 中定义一个搜索框的变量.
- export class CategoryComponent implements OnInit { public searchText:string;
- topCategoriesData=[]; thirdCategoriesData=[];
- isLoading = false;
- constructor(private categoryService:CategoryService) { } loadMore(id): void { this.isLoading = true; this.categoryService.getThirdById(id).subscribe((data:any) => { this.isLoading = false; this.thirdCategoriesData=data; }); }
- ngOnInit():void { this.categoryService.getCategoriesTop().subscribe( (data:any)=>{ this.topCategoriesData = data; }); }
}
<nz-input-group nzSearch nzSize="large" [nzSuffix]="suffixButton"> <input type="text" [(ngModel)]="searchText" nz-input placeholder="input search text"></nz-input-group><ng-template #suffixButton> <button nz-button nzType="primary" nzSize="large" nzSearch>Search</button></ng-template><br><br><nz-card *ngFor="let topData of topCategoriesData" nzTitle="{{topData.categoryName}}"> <div nz-card-grid [ngStyle]="gridStyle" *ngFor="let secondData of topData.subCategories | globalFilter: {categoryName: searchText,categoryCode: searchText}"> <nz-collapse> <nz-collapse-panel [nzHeader]="secondData.categoryName+'('+secondData.categoryCode+')'"[nzActive]="false"[nzDisabled]="false"> <nz-select style="width: 100%;"(nzOpenChange)="loadMore(secondData.categoryId)"nzPlaceHolder=" 请选择..."nzAllowClear> <nz-option *ngFor="let thirdData of thirdCategoriesData | globalFilter: {categoryName: searchText,categoryCode: searchText}"[nzValue]="thirdData.categoryId"[nzLabel]="thirdData.categoryName+'('+thirdData.categoryCode+')'"></nz-option> <nz-option *ngIf="isLoading" nzDisabled nzCustomContent> <i nz-icon type="loading" class="loading-icon"></i> Loading Data... </nz-option> </nz-select> </nz-collapse-panel> </nz-collapse> <!-- <a>{{secondData.categoryName}}</a><b>({{secondData.categoryCode}})</b> --> </div> <ng-template #extraTemplate> <a > 二级分类数量:{{data.subCategories.length}}</a> </ng-template></nz-card >
关键代码是: globalFilter: {categoryName: searchText,categoryCode: searchText}
其他代码都是为了完整而贴上去的.
结语
具体的实现思路是利用 filter + pipe 在数据集中进行过滤, 因为这里直接过滤的是数据集. 所以没办法单独设置过滤 HTML, 然后我遇到的问题是如果在一个包含有 2 级数据结构的 HTML 中应用的话, 会从 1 级开始匹配, 匹配到 2 级再结束. 但如果 1 级未匹配到则 2 级不再匹配. 例如: 你的 1 级数据为:"医药品",2 级数据为 "医药部外品","外用药品". 搜索词为: 医药部, 则不会显示任何结果.
最后附上本文的 参考链接
来源: https://juejin.im/post/5c010621e51d457cc205845f