Search code examples
angularpipenanngmodel

Pipe, ngModel and ngModelChange


I have a two-way data binding with a custom pipe.

My input text field code:

<input type="text" [ngModel]="post.price | myCurrencyPipe" (ngModelChange)="post.price = $event" name="price" id ="price" (change)="itemPriceUpdate(post)"/>

and custom pipe code :

@Pipe({ name: 'myCurrencyPipe'})
export class MyCurrencyPipe implements PipeTransform{

      transform(val:any) {
        var value = parseInt(data);
        var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
        return num;

      } 

When I go to edit my input field value it displays NaN on keypress.


Solution

  • This is because you have character $ at the front of val which added by your custom pipe. remove it before calling parseInt(data) will solve your problem.

    transform(val:any) {
      val = val.toString().replace(/[^0-9.]/g, '');
      if (val === '') return '';
      var value = parseInt(val);
      var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
      return num;
    } 
    

    plinker demo.