angular – 删除空间时,带管道的输入框不会更新值
我创建了一个管道来格式化输入框中的值,如下所示:
当我在输入框中键入或按下退格键时,管道会提供所需的输出. 问题:当我从“输入”框中删除空格时,输入框不会更新. 例如如果我将值从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(); } } } Plunker:https://plnkr.co/edit/j5tmNxllfZxP0EDp2XgL?p=preview 知道为什么会出现这种行为以及如何解决/解决这个问题? 解决方法
好的,最后在挖掘之后我找到了解决这个问题的方法.
因此,当管道返回新格式化的字符串时,它仍然与之前返回的字符串相同. 因此,我们需要使用一些角度魔法来实现这一目标. @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 Added'); console.log(value); return WrappedValue.wrap(value); } } 请注意,管道现在返回WrappedValue.wrap(value). 这表示即使引用未更改,管道转换的结果也已更改. 供参考:https://angular.io/docs/js/latest/api/core/index/WrappedValue-class.html Plunker:https://plnkr.co/edit/dhxtZrTeRKm2FSw5DIJU?p=preview (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |