我创建了一个管道来格式化输入框中的值,如下所示:
1 123
10 123
101 123
2 101 123
23 101 123
123101 123
当我在输入框中键入或点击退格键时,管道会给出所需的输出。
问题:当我从输入框中删除空格时,输入框不会更新。
例如,如果我将值从 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
知道为什么会有这种行为以及如何解决/处理这个问题吗?
好的,终于在挖掘之后,我找到了这个问题的解决方案。
因此,当管道返回新的格式化字符串时,它仍然与之前返回的字符串相同。
因此,我们需要使用一些角度魔法来实现这一目标。
@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)
。
这表示即使引用未更改,管道转换的结果也已更改。
供参考:https://angular.io/docs/js/latest/api/core/index/WrappedValue-class.html
普伦克:https://plnkr.co/edit/dhxtZrTeRKm2FSw5DIJU?p=preview