删除 space 后,带竖线的输入框不会更新值

Input box with pipe does not update value when space is removed

我创建了一个管道来格式化输入框中的值,如下所示:

1 123

10 123

101 123

2 101 123

23 101 123

123 101 123

当我在输入框中键入或回击时,管道会给出所需的输出space。

问题: 当我从输入框中删除 space 时,输入框没有更新。

例如如果我将值从 123 123 更改为 123123,则输入框不会更新。

管道:

@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" />

组件:

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

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

知道为什么会出现这种行为以及如何解决 fix/approach 这个问题吗?

好的,经过仔细研究,我终于找到了解决这个问题的方法。

因此,当管道 returns 新格式化的字符串时,它仍然与之前返回的字符串相同。

因此我们需要使用一些 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);
    }
}

现在注意管道 returns WrappedValue.wrap(value).

这表示管道转换的结果已更改,即使引用未更改。

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

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