首页 > 解决方案 > 如何管道搜索所有数据而不仅仅是名称?角

问题描述

我制作了一个运行良好的管道,但只搜索名称。我想搜索更多参数,包括:人口、地区和资本。检查我的代码:

    <div class="card d-flex flex-direction-column"
        *ngFor="let country of countries | country:searchTerm; let i=index">
        <img [src]="country.flag" alt="flag icon" style="width:100%">
        <div class="text-content white">
            <h4><b>{{ country.name }} </b></h4>

            <div class="d-flex align-items-center">
                <p class="unset-margin-p"> Population:&nbsp;</p> <span class="font-w-200">{{ fixNum(country.population) }}</span>
            </div>
            <div class="d-flex align-items-center">
                <p class="unset-margin-p"> Region:&nbsp;</p> <span class="font-w-200"> {{ country.region }} </span>
            </div>
            <div class="d-flex align-items-center">
                <p class="unset-margin-p"> Capital:&nbsp;</p> <span class="font-w-200"> {{ country.capital }} </span>
            </div>
        </div>
    </div>

和最重要的管道

export class CountryPipe implements PipeTransform {

  transform(country:any, searchTerm: string): HomeComponent { 
    if (!country || !searchTerm) {
      return country;
    }
    return country.filter(country =>
      country.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1);
  }

}

标签: javascripthtmlangular

解决方案


您可以传递一个包含要检查数组的值的对象,而不是简单地将单个字符串作为参数传递给管道。下面 stackblitz 中提供的实现非常丑陋,但强调了如何以最小的方式实现这一点。

https://stackblitz.com/edit/angular-4czmjr?file=src/app/sample.pipe.ts

此外,您的管道似乎返回一个数组而不是返回类型所暗示的组件。


推荐阅读