how to filter *ngFor result based on a selected dr

2020-02-11 09:55发布

问题:

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.

回答1:

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



回答2:

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;">


回答3:

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