0

I used this post to create a custom pipe and apply it to my reactive form. Applying a pipe or transform to a Reactive Form value

This works fine when loading the form, values are multiplied by a factor.

But it does not work the other way around when entering a number. E.g. when 10, with the factor beeing 1000, I would expect 10000 in {{ form.value | json }}

But this does not work. Does somebody know what I am doing wrong?

Kind regards!

Below you can see

  1. the pipe definition
  2. an excerpt of the reactive form for the field I am applying the pipe to
  3. the html template for that field

import {
  Pipe,
  PipeTransform
} from '@angular/core';

@Pipe({
  name: 'scaleInput'
})
export class ScaleInputPipe implements PipeTransform {

  transform(value: number, factor: number): number {
    const result: number = value / factor;
    return result;
  }

}

...

constructor(private _scaleInputPipe: ScaleInputPipe) {}

...

  this._formBuilder.group({
    expectedCashFlow: this._scaleInputPipe.transform(x.expectedCashFlow, 1000),
    hedgeRatio: x.hedgeRatio,
    ...
  })

<mat-form-field>

  <input formControlName="expectedCashFlow" [(ngModel)]="x.expectedCashFlow" #cf matInput type="number">

</mat-form-field>
baouss
  • 1,312
  • 1
  • 22
  • 52
  • @Alex Hey, where does he mix template driven form with reactive? For me he just uses input and output from `FormControlName` directive – yurzui Feb 08 '18 at 17:57
  • @yurzui Ah, sorry, well what I rather meant that using two bindings, formcontrol and ngModel. You are correct good Sir, my comment was not accurate :P – AT82 Feb 08 '18 at 18:00
  • Hi. I started only using formControlName="x"... The data is derived from a class of data which has some member methods like "reset" (with some business logic inside, not just emptying the values). When I called this method, the json representation of the form was effected, but not the visible values on-screen. Therefore I added the [ngModel] directive, to have programatically changes to the data also reflect in the UI... – baouss Feb 08 '18 at 21:40
  • Hi, I do have a solution... but I had to switch to a template driven form. Based on this SO post, I split [(ngModel)] into [ngModel] and (ngModelChange). Afaik, this is what is done behind the scenes anyway. Then I'm using my pipe in my [ngModel] binding expression and secondly run a function on (ngModelChange) that updates the value in the data model and applies a reverse version of the previous pipe. https://stackoverflow.com/questions/39642882/using-pipes-within-ngmodel-on-input-elements-in-angular2-view I didnt mark as solution because I had to switch from reactive to template – baouss Feb 09 '18 at 08:22

0 Answers0