Input field with channel does not update value when deleting space

I created a channel to format the value in the input field as follows:

1 123

10 123

101 123

2 101 123

23 101 123

123 101 123

The pipe gives the desired result when I enter into the input field or hit back.

Problem: The input field is not updated when a space is removed from the input field.

eg. If I change the value from 123 123 to 123123, the input field will not be updated.

Trumpet:

@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 is and how to fix / solve this problem?

+4
source share
1 answer

OK, finally, after digging, I found a solution to this problem.

, , , .

angular, .

@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);
    }
}

, WrappedValue.wrap(value).

, Pipe , .

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

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

+1

Source: https://habr.com/ru/post/1667350/


All Articles