Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
Angular 4 FilterBy Pipe

I'm trying to emulate what in AngularJS is OrderBy.

Given this this kind of array. I need to filter the cars by car_category.

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

Here is how my code looks so far

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

}

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

}

How does my pipe needs to be refactored?

UPDATE this is how my pipe looks right now. Note that the car is a number and the year is shown as a string

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

}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Writing custom generic pipes can be tricky. If you look at the Angular 1 source code, you'll get what I mean.

Therefore I suggest using a library, such as ng-pipes. To be honest I haven't tested the Angular 2 version, but it was quite handy for Angular 1.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda