mohammad
mohammad

Reputation: 2212

Angular 2 pipes dependency injection

Hi all I am new to angular 2, I am trying to create a custom pipe/filter,

but when I want to inject the pipe I created inside app.ts it is not doable as in the attached image enter image description here

my component code:

import { Component, OnInit ,Pipe, PipeTransform} from '@angular/core';
import { Input, Injectable, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import {Observable} from 'rxjs/Rx'
import {Filter} from '../filter.pipe';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css'],
  pipesp[Filter]
  
})

export class TestComponent implements PipeTransform  {
    private todos = ['wash dishes', 'Clean the ground','program the site', 'eat'];
  constructor() {
  }

   transform(value: any) {
    if (!value) {
      return '';
    }
    
  }
}

filter.pipe.ts code :

import  {Pipe, PipeTransform} from  '@angular/core';
@Pipe({name:'filter'})
export class Filter {
    transform(value,args){
        if(!args[0]){
            return value;
        }else if ( value){
            return value.filter(item => {
                for(let key in item){
                    if((typeof item[key] === 'string' || item[key] instanceof String) && (item[key].indexOf(args[0]) !==-1)){
                        return true;
                    }
                }
            });
        }
    }

}

test.component.html

<input type="text" [(ngModel)]="filterText">
<ul>
    <li *ngFor="let todo of todos | filter: filterText "> 
        {{todo}}
    </li>
</ul>

Upvotes: 0

Views: 773

Answers (3)

Majesty
Majesty

Reputation: 1919

Here is a solution

Write

@Component({
  pipes: [ filter ] 
})

But not

@Component({
  pipes[Filter]
})

Upvotes: 0

Pramod Patil
Pramod Patil

Reputation: 2763

You need to include Pipe Component in Ng Module(in root component module) and use it as globally in all components

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ SearchPipe ],
  bootstrap:    [ AppComponent ]
})

And use it in template directly

@Component({
  selector: 'my-app',
  template: '<p>My name is <strong>{{ name | search}}</strong>.</p>', 
})

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222682

You should inject the Pipe to the corresponding module as follows, and use it in the component

 declarations: [
    Filter
]

Upvotes: 1

Related Questions