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

I have a pipe class that returns data based on the arguments you pass. I know how to use it in my HTML template using the | but I want to use it in my component too.

Is there a way to call a pipe directly from within a component or service in Angular 2?

+4
source share
3 answers

You can call your pipe directly in your code using:

 YourPipeClass.prototype.transform(value, arg1, arg2); 

You can call it from your component or from another source that imports it.

There is also a new way:

 new SortTodosPipe().transform(value, arg1, arg2); 

But keep in mind that it will create an object, so either save this object for later use, or use the prototype method.

In any case, you should add the channel to your providers if you use it inside the component, for example:

 @NgModule({ providers: [YourPipe] }) 
+8
source

I would do that and call it the transform method. I would do this:

  • because some pipes may not be clean (that is, not without citizenship). Such pipes contain the state associated with the instance.
  • because dependency injection is supported for pipes, so maybe you need to provide some parameters when creating it.

Here is an example with a sample 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 will be used, for example, as follows:

 <div *ngFor="#elt of val | filter:'fieldName':'fieldValue'"> {{elt.name}} </div> 
+1
source

I would save a reusable part of what you are trying to do in a separate service, which can then be entered anywhere. It looks like a slippery slope towards something less verifiable and reusable.

0
source

Source: https://habr.com/ru/post/1013415/


All Articles