Angular 4 FilterBy Pipe

时间:2017-04-26 11:49:10

标签: angular typescript angular-pipe

我试图模仿AngularJS中的OrderBy。

鉴于这种阵列。我需要通过car_category过滤汽车。

[
  {
    "car_category": 3,
    "name": "Fusion",
    "year": "2010"
  },
  {
    "car_category": 2,
    "name": "Mustang",
    "year": "2010"
  },
  {
    "car_category": 3,
    "name": "Fiesta",
    "year": "2010"
  },
]

以下是我的代码到目前为止的样子

car.component.html

<div *ngIf="products">
  <ul *ngFor="let product of products | filterBy: car_category">
    <li>{{car.name}}</li>
  </ul>
</div>

car.component.ts

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
      );
  }

}

菲力-by.pipe.ts

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;
      }
    }
  });
}
  }

}

我的管道需要如何重构?

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

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;
      }
    }
  });
}
  }

}

1 个答案:

答案 0 :(得分:-2)

编写自定义通用管道可能很棘手。如果你看Angular 1 source code,你就明白了。

因此我建议使用库,例如​​ng-pipes。说实话,我还没有测试过RTPatch Executable版本,但它对Angular 2非常方便。