如何根据选定的下拉列值过滤* ngFor结果

时间:2017-07-23 15:48:47

标签: angular ionic-framework ionic3 ngfor

选择一个类别:

 <ion-select name="categories">
    <ion-option *ngFor="let category of categories;">
      {{category}}
    </ion-option>
  </ion-select>

列出项目:

 <ion-item-sliding *ngFor="let item of items; let idx = index;">
    <ion-item>
        <h2>{{item.title}}</h2>
    </ion-item>
...
</ion-item-sliding>

如何使用(select)中的值来选择列出的类别?我尝试添加一个ngModule并将其作为条件传递给滑动ngFor,但它不起作用。

3 个答案:

答案 0 :(得分:2)

您可以使用ngx-pipes库在阵列和字符串中进行令人难以置信的过滤和转换。

对于您的问题,您可以在ngx-pipes库中使用filterBy管道。

<ion-option *ngFor="let category of categories | filterBy:['name']:selectedVariable;">

答案 1 :(得分:1)

您可以使用管道来实现此目的

 <ion-item-sliding *ngFor="let item of items | categorySelected; let idx = index;">
    <ion-item>
        <h2>{{item.title}}</h2>
    </ion-item>
...
</ion-item-sliding>

在变换方法中,您可以执行逻辑

transform(s[],cat){
    ///logic

return filteredArray
}

Sample Plunker

更新1:完成答案

自定义管道将具有以下代码,

transform(records: Array<any>, property:any): any {
      let sortedArray=[];
      if(property){
      sortedArray =_.filter(records, {'office':property.Name]);
      console.log(sortedArray);
      return sortedArray
      }
  }

下拉列表和项目列表

<div>
  <select [(ngModel)]="selectedElement">
    <option *ngFor="let type of types" [ngValue]="type">
      {{type.Name}}</option>
  </select>
  <span *ngFor="let x of array | orderBy:selectedElement">{{x.firstName}}</span>
</div>

<强> LIVE DEMO

答案 2 :(得分:0)

你也可以简单地把

    ngOnChanges() {
       this.itemsForDisplay = this.items.filter(element => element.category = this.category);
    }

并在模板中显示itemsForDisplay,而不是items