angularangular2-pipeangular2-custom-pipes

Bind component variable to pipe filter


i have a problem when passing values to my pipe filter. I need to pass an argument value in the form of a variable called pagex from my component and I cant find the syntax to make it work... or I'm missing something. Thanks for the help.

myComponent

export class ItemsComponent { 
    items:any[]
    pagex:number;

constructor(private ItemService:ItemService){
    this.ItemService.getItems()
    .subscribe(items =>{
        this.items=items;
        this.pagex=2;
    });
}

The following, passing the value manually, works:

<div *ngFor="let item of items| myfilter: '2'">

and this doesnt, tried already many combinations...

<div *ngFor="let item of items| myfilter: {{pagex}}">
<div *ngFor="let item of items| myfilter: '{{pagex}}'">
<div *ngFor="let item of items| myfilter: {{pagex.toString()}}">
<div *ngFor="let item of items| myfilter: pagex>
<div *ngFor="let item of items| myfilter:'pagex'>

mypipe

@Pipe({
    name: 'myfilter',
})
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], args: any[]): any {
        if(items!=undefined){

        console.log(args[0])
        var maxItems = 5;
           var start_index= (args[0]*maxItems)-maxItems-1;
           var end_index= args[0]*maxItems;
    return items.filter((item, index) => (index > start_index) && (index <end_index));
    }
}

}


Solution

  • You have made mistake in the filter input's type.

    The parameters to the filter must be of number type and not any[ ]

    import{PipeTransform,Pipe} from '@angular/core';
    
    @Pipe({
        name:'myFilter'
    })
    
    export class myFilter implements PipeTransform{
    
        transform(inputDate:string,integerValue:number):string{
          console.log(integerValue);
    
          return integerValue.toString();             
        }
    }
    

    I dont know what is the filter doing exactly and there is no service implemented. So I tried this way. You can check the plunker below

    LIVE DEMO