在NativeScript中使用angular2过滤ListView

时间:2016-12-13 05:43:33

标签: nativescript angular2-nativescript

我是nativescript和angular2的新手。我想使用用户输入的文本字段输入来过滤listview。在角度版本1中,我们曾经像

那样做
<input type="text" ng-model="userinput">
<div ng-repeat="x in items | filter : userinput">
</div>

如何在nativescript中使用angular2来做到这一点?

我的列表视图是:

<ListView [items]="myItems" class="list-group">
<template let-item="item">
    <StackLayout>
        <Label [text]='item.Department' class="list-group-item"></Label>
    </StackLayout>
</template>
</ListView>

在我的组件中:

export class someComponent {

public myItem: Array<any>;
public isLoading: boolean;

public constructor(private http: Http) {
    this.myItem = [];
    this.isLoading = true;
}

public ngOnInit()
{
    this.http.get("some_api_url")
        .map(result => result.json())
        .do(result => console.log(JSON.stringify(result)))
        .subscribe(result => {
            this.myItem = result;
            this.isLoading = false;
        }, error => {
            console.log("ERROR: ", error);
        });
}
}

2 个答案:

答案 0 :(得分:0)

您必须先创建一个用于过滤的管道,例如:

@Pipe({
    name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
    transform(items: any[], field : string, value : string): any[] {  
        if (!items) return [];        
        return items.filter(it => it[field] == value);
    }
}

用法:

<li *ngFor="let it of its | filter : 'name' : 'value or variable'">{{it}}</li>

答案 1 :(得分:0)

当数据巨大时,nativescript ui listview过滤会很慢,并且会“删除”不匹配的项目。我更改了位代码以使其快速运行,并且仅显示过滤后的数据。 :) 快乐的编码:)

Page class="page">
    <StackLayout orientation="vertical">
        <GridLayout rows="auto,auto,*,auto">
            <StackLayout class="form" row="0" orientation="horizontal" width="100%">
                <TextField hint="Search..." class="input"
                           id= "searchstr"  
                          [(ngModel)]="searchstr" 
                           width="80%"></TextField>
                <Button class="btn-sm btn-primary btn-active" 
                        id="btnSearch" 
                        (tap)="onSearchTap($event)"
                        width="20%" height="40" >
                    <FormattedString>
                        <Span [text]="iconval" class="icon"></Span>
                    </FormattedString>  
                </Button>
            </StackLayout>
            <StackLayout row="1" orientation="horizontal" width="100%" backgroundcolor="black">
                    <Label text="CODE" width="25%" class="caption"></Label>
                    <Label text="NAME" width="75%" class="caption"></Label>                    
                </StackLayout>
            <ScrollView row="2" tkExampleTitle tkToggleNavButton>
                    <RadListView [items]="dataItems" 
                           (itemLoading)="onItemLoading($event)">     
                        <ListViewLinearLayout 
                             tkListViewLayout scrollDirection="Vertical" 
                             itemInsertAnimation="Slide" 
                             itemDeleteAnimation="Slide"></ListViewLinearLayout>                   
                        <ng-template tkListItemTemplate let-item="item" let-i="index" let-odd="odd" let-even="even">  
                           <StackLayout class="list-item" 
                                       (tap)="onItemTap(item)"
                                        orientation="horizontal" width="100%">
                                <Label [text]="item.custCode" width="25%"></Label>
                                <Label [text]="item.custName" width="75%"></Label>

                           </StackLayout>
                        </ng-template>                        
                    </RadListView>
          </ScrollView>
        </GridLayout>
    </StackLayout>
</Page>

import { Component, OnInit } from '@angular/core';
import { ListViewEventData } from 'nativescript-ui-listview';
import { Color } from 'tns-core-modules/color/color';
import { APIService } from '~/app/core/services';
import { Observable } from 'rxjs';
import { CustProfileLight } from '~/app/core/model';
import { ObservableArray } from 'tns-core-modules/data/observable-array/observable-array';


@Component({
  selector: 'ns-customer-lookup',
  templateUrl: './customer-lookup.component.html',
  styleUrls: ['./customer-lookup.component.css'],
  moduleId: module.id,
})
export class CustomerLookupComponent implements OnInit {
  private _dataItems: ObservableArray<CustProfileLight>;
  customer$:Observable<CustProfileLight>
  iconval:string;
  search:string;
  searchstr:string;
  items:any;

  //private _myFilteringFunc: (item: any) => any;

  constructor(private serv:APIService) { }

  ngOnInit() {
    this.iconval = String.fromCharCode(0xe986);
    this.serv.getCustomer().subscribe(resp=>{
       this.items = resp;
       this._dataItems = new ObservableArray<CustProfileLight>(resp);
    })    
  }

  get dataItems(): ObservableArray<CustProfileLight> {
    return this._dataItems;
  }

  onItemLoading(args: ListViewEventData){
    if (args.index % 2 === 0) {
       args.view.backgroundColor = new Color("#b3ecff");      
    }
 }

  onItemTap(item){

  }

  onSearchTap(e){
    const key =this.searchstr;
    console.log(key);
    let data= this.items.filter(item=>item.custCode.includes(key) ||
                            item.custName.includes(key) ||
                            item.address1.includes(key) ||
                            item.address2.includes(key) ||
                            item.address3.includes(key) ||
                            item.address4.includes(key) ||
                            item.city.includes(key) ||
                            item.state.includes(key) ||
                            item.postalCode.includes(key) ||
                            item.tel.includes(key) ||
                            item.fax.includes(key) ||
                            item.contactPerson.includes(key)
                    );

     this._dataItems = new ObservableArray<CustProfileLight>(data);                

  }

  // get FilteringFunc(): (item: any) => any {
  //   return this._myFilteringFunc;
  // }

  // set FilteringFunc(value: (item: any) => any) {
  //    this._myFilteringFunc = value;
  // }
}