将逗号分隔的千位添加到Angular2中的数字输入中 [英] Add Comma Separated Thousands to Number Inputs in Angular2
问题描述
在Angular 2中,如何为数字输入控件添加千位分隔符,例如
In Angular 2 how would I add thousands separator for number input controls, so for example
模型1000中的值
当光标不在输入控件显示分隔符中(例如1,000)
When cursor not in input control display separator (e.g. 1,000)
在输入控件中编辑值(即控件内部的光标)时,应删除逗号以使值易于编辑
When editing value (i.e. cursor inside control) in input control, it should remove commas to allow the value to be easily edited
谢谢
推荐答案
正如Mark上面所述,您想使用管道.您可以使用以下语法创建管道,然后只需使用组件装饰器上的pipes
属性将管道添加到您的组件中即可.
As Mark commented above you want to use a pipe. You can create a Pipe using the following syntax, then simply add the pipe to your component using the pipes
property on the component decorator.
@Pipe({name: 'commaSeparatedNumber'})
export class CommaSeparatedNumberPipe implements PipeTransform {
transform(value:number, args:string[]) : any {
return // Convert number to comma separated number string
}
}
@Component({
...
template: `
<div *ngIf="!editing">{{number | commaSeparatedNumber}}</div>
<input type="number" [(ngModel)]="number" />
`,
pipes: [CommaSeparatedNumberPipe]
})
class MyComponent{
public editing: boolean;
public number: number;
...
}
更新
在这种情况下,我建议听输入中的焦点和模糊事件
In that case I would recommend listening to the focus and blur events on the input
@Component({
...
template: `<input type="text" [(ngModel)]="number"
(focus)="removeCommas()" (blur)="addCommas()" />`
})
class MyComponent{
number: string;
removeCommas(){
this.number = this.number.replace(',', '');
}
addCommas(){
this.number = // Convert number to comma separated number string
}
}
这篇关于将逗号分隔的千位添加到Angular2中的数字输入中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!