How to use a pipe in a component in Angular 2?

后端 未结 4 1311
终归单人心
终归单人心 2021-01-12 05:22

I have a pipe class which returns data based on the arguments you are passing. I know how to use it in my template HTML using the | symbol, but I want to use it

4条回答
  •  青春惊慌失措
    2021-01-12 06:01

    I would instance it and call it "transform" method. I would do so:

    • because some pipes can be not pure (i.e. not stateless). Such pipes contain a state associated with an instance.
    • because dependency injection is supported for pipes so perhaps you need to provide some parameters when instantiate it.

    Here is a sample with sample value and parameters:

    import {FilterPipe} from './my.pipe';
    
    (...)
    
    @Component({
      (...)
    })
    export class SomeComponent {
      someMethod() {
        var val = [
          { name: 'test', fieldName: 'fieldvalue' },
          (...)
        ];
        var params = [ 'fieldName', 'fieldValue' ];
    
        var p = new FilterPipe();
        var result = p.transform(val, params);
      }
    }
    

    In the template this would be used for example this way:

    {{elt.name}}

提交回复
热议问题