简体   繁体   中英

Angular2 pipes dependency injection

hi all i am new to anguler 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 在此处输入图片说明

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>

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

 declarations: [
    Filter
]

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>', 
})

Here is a solution

Write

@Component({
  pipes: [ filter ] 
})

But not

@Component({
  pipes[Filter]
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM