Search code examples
angularangular6angular-directivengfor

How to use @Input to set a Pipe in a *ngFor directive


I have a component that has 3 input parameters

  1. json_columns
  2. json_rows
  3. name_filter

How can I make it so the name_filter is set as the pipe to filter that group of data?

component.ts

@Input('json_columns') columns:[{}];
@Input('json_rows') rows:[{}];

//Pipe 
@Input('name_filter') filter:string;

component.html

<tr *ngFor="let item of filas | filter: searchItem; let i=index" >
{{item.nombre}}
</tr>

Solution

  • One way to do this is to create a function ‘getFilas()’ and implement the filter in the function

    See this example: https://stackblitz.com/edit/angular-filter-data-in-component

    This is the template

    <div *ngFor="let item of getData(); let i=index">
        {{i}} -  {{item.name}} {{ item | json }}
    </div>
    

    This is the relevant code in the component

      @Input() field: string;
      @Input() value: string;
      @Input() data: any[];
    
      getData() {
        return this.data.filter((item) => {
          return item[this.field] == this.value;
        })
      }