将组件变量绑定到管道过滤器

时间:2017-01-11 16:25:44

标签: angular angular2-pipe angular2-custom-pipes

将值传递给管道过滤器时出现问题。我需要从我的组件中传递一个名为pagex的变量形式的参数值,我无法找到使其工作的语法......或者我错过了一些东西。谢谢你的帮助。

myComponent的

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

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

以下操作:手动传递值:

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

这并没有,尝试过很多种组合......

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

}

2 个答案:

答案 0 :(得分:1)

您在过滤器输入的类型中犯了错误。

过滤器的参数必须是数字类型,而不是任何[]

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

我不知道过滤器究竟做了什么,没有实现服务。所以我试过这种方式。你可以检查下面的plunker

LIVE DEMO

答案 1 :(得分:0)

EDIT。试试这个,似乎你错过了:' '

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