Angular6-Filter實現頁面搜尋
前言
我們在開發過程中經常會遇到在頁面上實現全域性搜尋的需求,例如:表格搜尋,通過關鍵詞檢索整個表格,過濾出我們需要的資料。在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級資料為“醫藥部外品”,“外用藥品”。搜尋詞為:醫藥部,則不會顯示任何結果。
最後附上本文的參考連結
最後,感謝閱讀。本文如有不對的地方,還請指正。
後續考慮將angular6 中一些實際應用整理成系列文章,歡迎大家一起探討。