Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data to custom pipe from component in angular 2

Tags:

angular

pipe

How can I pass data to custom pipe from the component?
I am trying to bind the form data to the component and pass to the pipe.

<input [(ngModel)]="phone" placeholder="Phone Number">

want to pass 'this.phone' to 'PhoneNum' pipe from the component.

This is done in template.
{{phoneNumber | PhoneNum}} // PhoneNum is the pipe

My question is done in AngularJS in this way from the controller

<input ng-model="phone placeholder="Phone Number">
$filter(‘PhoneNum’)($scope.phone); // something like this.
Appreciate the Time!

like image 261
Sachin Avatar asked Jan 10 '16 23:01

Sachin


2 Answers

Since a pipe is just a class that implements the PipeTransform interface, you can register it with the component's injector through the providers property:

import { MyPipe } from './my.pipe.ts';

@Component({
   ...
   providers:[MyPipe]
})

Then you can inject the Pipe into any component's (or child component's) constructor through DI and use it by calling the transform method:

export class MyComponent {
   private filteredData:Data[];
   constructor(private mypipe:MyPipe) {
       var data = [...];
       this.filteredData = this.mypipe.transform(data, []);
   }
};

Or if you don't want to register it through DI, you can just instantiate the Pipe when you need it:

export class MyComponent {
   private filteredData:Data[];
   constructor() {
       var data = [...];
       this.filteredData = new MyPipe().transform(data, []);
   }
};
like image 165
pixelbits Avatar answered Sep 26 '22 16:09

pixelbits


I don't think you can do that with two-way data binding, but you can break it into two one-way bindings and filter one of them through your pipe:

<input [ngModel]="phone" (ngModelChange)="phone = PhoneNum.transform($event)">

or you can leave the original propery just the way it is and call the pipe in the getter of the property:

template:

<input type="text" [(ngModel)]="phone">

component:

private _phone:string = 'test';

public get phone(){ return this.PhoneNum.transform(this._phone); }

public set phone(phone){ this._phone = phone; }
like image 41
Langley Avatar answered Sep 26 '22 16:09

Langley