how to filter *ngFor result based on a selected dr

2020-02-11 09:45发布

Choosing a category:

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

Listing the items:

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

How can I use the value from (select) to choose which category gets listed? I tried adding a ngModule in and passing it as a condition into the sliding ngFor, but it wouldn't work.

3条回答
够拽才男人
2楼-- · 2020-02-11 10:04

You can use a pipe to achieve this

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

In your transform method you can perform your logic

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

return filteredArray
}

Sample Plunker

Update 1 : Complete answer

Custom pipe will have the below code,

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

Dropdown and list of items

<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

查看更多
干净又极端
3楼-- · 2020-02-11 10:06

You can also simply put

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

and display itemsForDisplay in your template instead of items

查看更多
Viruses.
4楼-- · 2020-02-11 10:12

you can use ngx-pipes library for doing incredible filtering and transforming in arrays and strings.

for your Question you can use filterBy pipe in ngx-pipes library.

<ion-option *ngFor="let category of categories | filterBy:['name']:selectedVariable;">
查看更多
登录 后发表回答