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!
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, []);
}
};
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With