Home > Mobile >  Angular: select filter with pipe not working in diferent components
Angular: select filter with pipe not working in diferent components

Time:07-08

I have 2 components, one in which I have a filter with select and another component with a table where I load data with an API. I´ve created a Pipe to filter data in the table with the select, but being in two different components it doesn´t work for me. It works for me if I have both, the select and the table, in the same component. Is there a way to make the Pipe work by having the select and the table in separate components? Thanks.

Select html

 <select  [(ngModel)]="buscarporRegion">
        <option value="">Regiones</option>
        <option value="{{region.region}}" *ngFor="let region of paises">{{region.region}}</option>

table html

  <tbody>
        <tr *ngFor="let pais of paises |buscarRegion:buscarporRegion">
          <td>{{ pais.region }}</td>
          <td> {{ pais.name }}</td>
          <td>{{ pais.capital }}</td>
        </div>
        </tr>
        </tbody>

Select ts

  export class CardComponent implements OnInit {

   buscarporRegion = '';

table ts

  export class TableComponent implements OnInit {

   buscarporRegion = '';

Pipe

  @Pipe({
  name: 'buscarRegion'
})
export class BuscarRegionPipe implements PipeTransform {

  transform(value: any, arg: any): any {
    const buscarporregion = [];
    for (const recorrido of value) {
      if(recorrido.region.toLowerCase().indexOf(arg.toLowerCase()) > -1){
        buscarporregion.push(recorrido);
      }
    }
    return buscarporregion;
  } 

CodePudding user response:

Pass the buscarporRegion from CardComponent to TableComponent by declaring Input() decorator in TableComponent.

Table.ts

import { Input } from '@angular/core';

export class TableComponent implements OnInit {

  @Input() buscarporRegion = '';

}

Select.html

Assume that the TableComponent selector is app-table.

<!-- Select dropdown -->

<app-table [buscarporRegion]="buscarporRegion"></app-table>

While I think the BuscarRegionPipe filtering logic can be simplified with .filter().

transform(value: any, arg: any): any {
    return value.filter(x => x.region.toLowerCase() == arg.toLowerCase());
}
  • Related