praveen
praveen

Reputation: 228

How to apply pipe to form control value while patching in angular2

I am using reactive forms approach of angular 2 in my current application. i am having many input fields, i am patching the json which i got from server.

now i got a requirement like i have to format the value while displaying and send the actual value while sending.

eg: input currency fields has to format in currency type with commas and while sending it is just a number.

How can i achieve this.

i need both value and display value to the form control. .

 <input type="text"  data-test="yearlyRevenue" formControlName="yearlyRevenue" [numberformat]="18" >

    numberformat is my custom directive to format the data

Upvotes: 0

Views: 1413

Answers (1)

Eliseo
Eliseo

Reputation: 57981

In blog.ngconsultant.io you have an example.

the "key" is use a Hotlistener when a "blur" and a "focus" happened. If you have two function "transform" and "parse" you can do

ngOnInit() {
    this.el.value = this.transform(this.el.value);
}

@HostListener("focus", ["$event.target.value"])
onFocus(value) {
   this.el.value = this.parse(value); // opossite of transform
 }

@HostListener("blur", ["$event.target.value"])
  onBlur(value) {
    this.el.value = this.transform(value);
}

Upvotes: 1

Related Questions