使用Angular中的管道过滤多个属性

时间:2018-09-19 16:03:03

标签: angular typescript

我使用了tutorial来从结果表中使用单个属性(名称)过滤搜索,以及我希望它如何出色地发挥作用,但是如何适应管道以进行搜索多个属性(即SpeciesName,EnclosureName等)?

管道:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(items: any[], searchText: string): any {
    if(!items) return [];
    if(!searchText) return items;
    searchText = searchText.toLowerCase();
    return items.filter( it => {
      return it.Name.toLowerCase().includes(searchText);
    });
  }

}

HTML:

<section>
    <div class="toolbar">
        <input id="fur-filter" [(ngModel)]="searchText" class="filter" placeholder="FILTER ANIMALS, SPECIES, ENCLOSURES, TEMPERAMENTS ETC." />
        <button id="AddNewAnimal" class="ko-btn">Add New Animal</button>
        <button id="InspectionReport" class="ko-btn">Start Inspection Report</button>
    </div> 
    <div class="list-container">
      <div class="animal-row" *ngFor="let furries of animalsFur | filter : searchText">
        <img [src]="furries.avatar" />
        <div class="animal-info">
          <p>{{furries.Name}} {{furries.Nickname}}</p>
          <div class="row">
            <div id="species" class="col">
              <p id="species-text">Species: <span>{{furries.SpeciesName}}</span></p>
            </div>
            <div class="col">
              <p>Sub-Species: <span>{{furries.SubSpeciesName}}</span></p>
            </div>
            <div class="col">
              <p>Arrived: <span>{{furries.Welcomed}}</span></p>
            </div>
            <div class="col">
              <p>Age: <span>{{furries.Age}} Years</span></p>
            </div>
            <div class="col">
              <p>Enclosure: <span>{{furries.EnclosureName}}</span></p>
            </div>
            <div class="col">
              <p>Temperament: <span>{{furries.Temperament}}</span></p>
            </div>
          </div>
        </div>
      </div>
     </div>
  </section>

2 个答案:

答案 0 :(得分:1)

将return语句替换为:

return it.Name.toLowerCase().includes(searchText)||
it.Nickname.toLowerCase().includes(searchText)||
it.SpeciesName.toLowerCase().includes(searchText)||
.
.
.
.
;

答案 1 :(得分:1)

您只需使用&&(和)或||(或)来解决此问题:

return items.filter( it => {
    return it.Name.toLowerCase().includes(searchText) 
    || it.SpeciesName.toLowerCase().includes(searchText) // add more conditions
});