4

I have created a pipe to format the value in the input box as follows:

1 123

10 123

101 123

2 101 123

23 101 123

123 101 123

The pipe gives the desired output when I type into the input box or hit backspace.

Issue: The input box does not update when I remove a space from the Input box.

e.g. If I changed value from 123 123 to 123123 the input box does not update.

The pipe:

@Pipe({name: 'formatCurrency'})
export class FormatCurrencyPipe implements PipeTransform{

    transform(value: string): string {
        //convert to string
        value = value.toString();

        // remove spaces
        value = value.replace(/ /g,'');
        console.log('Spaces removed');
        console.log(value);

        // add spaces
        value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
        console.log('Spaces Added');
        console.log(value);

        return value;
    }
}

HTML:

<input type="text" (keypress)="disableSpace($event)" [ngModel]="data.value | formatCurrency" (ngModelChange)="data.value = $event" />

Component:

export class App implements OnInit {
  name:string;
  data:any = {value: 123345};
  constructor() {}

  ngOnInit(): void {
     this.name = 'Angular2';
  }

  disableSpace(event: any) {
      if (event.charCode && event.charCode === 32 || event.which && event.which === 32) {
          event.preventDefault();
      }
  }
}

Plunker: https://plnkr.co/edit/j5tmNxllfZxP0EDp2XgL?p=preview

Any idea why this behavior and how to fix/approach this problem?

JSNinja
  • 705
  • 6
  • 19

1 Answers1

1

OK, finally after digging around I've found the solution to this problem.

So when the pipe returns the new formatted string it is still the same as the one it returned earlier.

Therefore we need to use some angular magic to get this going.

@Pipe({name: 'formatCurrency'})
export class FormatCurrencyPipe implements PipeTransform{

    transform(value: string): string {
        //convert to string
        value = value.toString();

        // remove spaces
        value = value.replace(/ /g,'');
        console.log('Spaces removed');
        console.log(value);

        // add spaces
        value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
        console.log('Spaces Added');
        console.log(value);

        return WrappedValue.wrap(value);
    }
}

Note the pipe now returns WrappedValue.wrap(value).

This indicates that the result of a Pipe transformation has changed even though the reference has not changed.

For reference: https://angular.io/docs/js/latest/api/core/index/WrappedValue-class.html

Plunker: https://plnkr.co/edit/dhxtZrTeRKm2FSw5DIJU?p=preview

JSNinja
  • 705
  • 6
  • 19