使用自定义搜索字词过滤RadListView

时间:2019-01-30 16:59:41

标签: angular nativescript nativescript-angular radlistview

是否可以将过滤函数传递给可以访问局部变量“ searchTerm”的Angular Nativescript RadListView?我从here提供的示例中进行了尝试,但是该示例建议使用的是静态搜索字词。

我想要做的与样本过滤器功能不同的事情

样品

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

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

TypeScript

  // 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>

1 个答案:

答案 0 :(得分:1)

您可以简单地使用具有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;
    }
}