首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角4 FilterBy管

角4 FilterBy管
EN

Stack Overflow用户
提问于 2017-04-26 11:49:10
回答 1查看 4K关注 0票数 2

我试图模仿AngularJS中的OrderBy。

考虑到这类数组。我需要用car_category过滤汽车。

代码语言:javascript
复制
[
  {
    "car_category": 3,
    "name": "Fusion",
    "year": "2010"
  },
  {
    "car_category": 2,
    "name": "Mustang",
    "year": "2010"
  },
  {
    "car_category": 3,
    "name": "Fiesta",
    "year": "2010"
  },
]

到目前为止,我的代码如下所示

car.component.html

代码语言:javascript
复制
<div *ngIf="products">
  <ul *ngFor="let product of products | filterBy: car_category">
    <li>{{car.name}}</li>
  </ul>
</div>

car.component.ts

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { CarService } from '../car.service';
import { ICars } from '../ICars';
import { FilterByPipe } from '../filter-by.pipe';

@Component({
  selector: 'app-home-page',
  templateUrl: './car.component.html',
  styleUrls: ['./car.component.css']
})
export class CarComponent implements OnInit {
  cars: Array<ICars>;
  errorMessage: string;
  filteredCars: any;
  car_category= 3;

  constructor(private _carService: CarService) { }
  ngOnInit() {
     this._carService.getCars()
      .subscribe(
        cars => this.cars = cars,
        error => this.errorMessage = error
      );
  }

}

filet-by.pipe.ts

代码语言:javascript
复制
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {

  transform(value, args) {
    if (!args[0]) {
      return value;
    } else if (value) {
      return value.filter(item => {
        // tslint:disable-next-line:prefer-const
        for (let key in item) {
          if ((typeof item[key] === 'string' || item[key] instanceof String) &&
            (item[key].indexOf(args[0]) !== -1)) {
        return true;
      }
    }
  });
}
  }

}

我的烟斗需要怎么改造?

更新--这就是我的管道现在的样子。请注意,这辆车是一个数字,年份显示为字符串。

代码语言:javascript
复制
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {

  transform(value, args) {
    if (!args[0]) {
      return value;
    } else if (value) {
      return value.filter(item => {
        // tslint:disable-next-line:prefer-const
        for (let key in item) {
          if ((typeof item[key] === 'number' || item[key] instanceof Number) &&
            (item[key].indexOf(args[0]) !== -1)) {
        return true;
      }
    }
  });
}
  }

}
EN

回答 1

Stack Overflow用户

发布于 2017-04-26 13:01:21

编写自定义通用管道可能很棘手。如果你看看源代码,你就会明白我的意思。

因此,我建议使用一个库,例如五管。老实说,我还没有测试过Angular 2版本,但这对于Angular 1来说非常方便。

票数 -3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43633367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档