首页 > 解决方案 > 使用自定义搜索词过滤 RadListView

问题描述

是否可以将过滤函数传递给可以访问局部变量“searchTerm”的Angular Nativescript RadListView?我已经尝试过此处提供的示例,但是该示例建议的是静态搜索词。

我希望对样本过滤器功能做不同的事情;

样本

this.myFilteringFunc = (item: DataItem) => {
    return item && item.name.includes("Special Item");
};

我正在将搜索词修改"Special Item"为用户输入的文本框。我试过的是;

打字稿

  // on inital load....
  this.resultsFound = this._dataItems 
                      && this._dataItems.length > 0 
                      && this._dataItems.filter(c => (c.Firstname && c.FirstName.includes(this.searchTerm)) 
                                                    || (c.LastName && c.LastName.includes(this.searchTerm))
                                                ).length > 0;
  if (this.searchTerm.length > 0) {
      if(this.resultsFound) listView.filteringFunction = this.filterByName.bind(this);
  } 
  else {
      listView.filteringFunction = undefined;
  }



//...later, I define the filtering function like so;
filterByName(item: NameListViewModel) {
    if (!this.searchTerm){
      return true;
    }
    return item 
            && ((item.FirstName && item.FirstName.includes(this.searchTerm))
                || (item.LastName && item.LastName.includes(this.searchTerm)));

};

看法

<RadListView #myListView row="0" *ngIf="resultsFound" [items]="dataItems" [groupingFunction]="groupByAge" (itemLoading)="onItemLoading($event)">
    <ng-template tkListItemTemplate let-item="item" let-i="index">
        <StackLayout class="person-card">
            <app-person-register-list-item [item]="item"></app-person-register-list-item>
        </StackLayout>
    </ng-template>
    <ng-template tkGroupTemplate let-category="category">
        <StackLayout orientation="horizontal" [ngClass]="{'neutral-background':getCount(category)==''}" [ngClass]="{'grouping-header':getCount(category)!=''}" ios:height="50">                        
            <Label class="person-group-header" text="{{formatCategory(category)}}"></Label>
            <Label class="person-number" text="{{getCount(category)}}" verticalAlignment="center"></Label>
        </StackLayout>
    </ng-template>
</RadListView>

标签: angularnativescriptnativescript-angularradlistview

解决方案


您可以简单地使用带有items属性绑定的过滤器管道。

<RadListView [items]="dataItems | filter:filterText" ...>

filterText可能是您的动态输入。过滤管可能看起来像

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
    name: "filter"
})
export class FilterPipe implements PipeTransform {

    transform(source: any, filterText: string): any {
        if (!filterText) {
            return source;
        }

        const result: Array<any> = new Array<any>(),
            filterReg: RegExp = new RegExp(filterText, "i");

        source.forEach((item) => {
            if (filterReg.test(item.title)) {
                result.push(item);
            }
        });

        return result;
    }
}

推荐阅读