Angular Filter实现页面搜索
前言
本文代碼基于angular v6.x 以上。
我們?cè)陂_發(fā)過(guò)程中經(jīng)常會(huì)遇到在頁(yè)面上實(shí)現(xiàn)全局搜索的需求,例如:表格搜索,通過(guò)關(guān)鍵詞檢索整個(gè)表格,過(guò)濾出我們需要的數(shù)據(jù)。在Angular6 中我們可以通過(guò)Filter + Pipe 的方式來(lái)實(shí)現(xiàn)這個(gè)功能。下面我們看一下實(shí)現(xiàn)代碼。
經(jīng)人提醒,代碼排版太亂。后續(xù)考慮將一個(gè)完整版的demo放到GitHub上,敬請(qǐng)期待。
目前可參考我語(yǔ)雀上的文檔,Value-語(yǔ)雀。
實(shí)現(xiàn)代碼
第一步
新建一個(gè)名為 filter.pipe.ts 的文件,這部分是實(shí)現(xiàn)的核心代碼:
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] == ""; }); }); } } }}復(fù)制代碼代碼部分的正則表達(dá)式可以根據(jù)需要替換,這里是全局匹配。
第二步
在app.module.ts 文件中導(dǎo)入。
import { GlobalFilterPipe } from './shared/filter.pipe';import { BrandComponent } from './brand/components/brand.component' registerLocaleData(zh);@NgModule({ declarations: [ CategoryComponent, LayoutComponent, DashbordComponent, LeftNavComponent, GlobalFilterPipe, BrandComponent ], imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, HttpClientModule, NgZorroAntdModule, AppRoutingModule ], providers: [{ provide: NZ_I18N, useValue: zh_CN }], bootstrap: [LayoutComponent]})export class AppModule { } 復(fù)制代碼第三步
在需要的html 文件中應(yīng)用,在 componet 中定義一個(gè)搜索框的變量。
import { Component, OnInit } from '@angular/core';import { CategoryService } from '../category.service'; @Component({ selector: 'app-category', templateUrl: '../pages/category.component.html', styleUrls: ['../pages/category.component.css']})export class CategoryComponent implements OnInit { //todo 搜索無(wú)法由下至上匹配1,2級(jí)數(shù)據(jù) 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; }); } }復(fù)制代碼<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="請(qǐng)選擇..." 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>二級(jí)分類數(shù)量:{{data.subCategories.length}}</a> </ng-template></nz-card>復(fù)制代碼關(guān)鍵代碼是:globalFilter: {categoryName: searchText,categoryCode: searchText}
其他代碼都是為了完整而貼上去的。
結(jié)語(yǔ)
具體的實(shí)現(xiàn)思路是利用 filter + pipe 在數(shù)據(jù)集中進(jìn)行過(guò)濾,因?yàn)檫@里直接過(guò)濾的是數(shù)據(jù)集。所以沒(méi)辦法單獨(dú)設(shè)置過(guò)濾html,然后我遇到的問(wèn)題是如果在一個(gè)包含有2級(jí)數(shù)據(jù)結(jié)構(gòu)的html中應(yīng)用的話,會(huì)從1級(jí)開始匹配,匹配到2級(jí)再結(jié)束。但如果1級(jí)未匹配到則2級(jí)不再匹配。例如:你的1級(jí)數(shù)據(jù)為:“醫(yī)藥品”,2級(jí)數(shù)據(jù)為“醫(yī)藥部外品”,“外用藥品”。搜索詞為:醫(yī)藥部,則不會(huì)顯示任何結(jié)果。
最后附上本文的?參考鏈接,感謝閱讀。本文如有不對(duì)的地方,還請(qǐng)指正。
后續(xù)考慮將angular6 中一些實(shí)際應(yīng)用整理成系列文章,歡迎大家一起探討。
總結(jié)
以上是生活随笔為你收集整理的Angular Filter实现页面搜索的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 编译安装 PHP 扩展 - 含 swoo
- 下一篇: 针对表单的事件;条件语句;定时器的简单介