I have a use case in which there is a input text element in which if a person enters 2345 it should be displayed as 2,345 but in back end it should store the number as 2345. How could we achieve this in Angular 2?
3 Answers
Using angular inbuilt filter pipe for numbers will do it https://docs.angularjs.org/api/ng/filter/number
{{1234 | number}}
Output
1,234
2 Comments
Mayank Gupta
I think we can't use pipes on input elements
You can make a directive, that use @HotListener blur and focus
@Directive({ selector: "[app-number]" })
export class NumberFormat implements OnInit {
private el: HTMLInputElement;
constructor(private elementRef: ElementRef) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
this.el.value = this.transform(this.el.value);
}
@HostListener("focus", ["$event.target.value"])
onFocus(value) {
this.el.value = this.parse(value); // opossite of transform
}
@HostListener("blur", ["$event.target.value"])
onBlur(value) {
this.el.value = this.transform(value);
}
//value --> value formatted
transform(value:any)
{
...return your value formated...
}
//value formated--> value
parse(valueFormated:any){
..return the real value....
}
1 Comment
Mayank Gupta
I also made one custom directive which was formatting the input on key down event and formatting the input as the user types but the problem began when I tried to get the value of the input after user tabs out. Fetched value contains commas which is causing other functionality to break as they are expecting only a number.
Hope this would be useful:
Index.html:
<body ng-app="numberFilterExample">
<script>
angular.module('numberFilterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = 1234.56789;
}]);
</script>
<div ng-controller="ExampleController">
<label>Enter number: <input ng-model='val'></label><br>
Default formatting: <span id='number-default'>{{val | number}}</span><br>
No fractions: <span>{{val | number:0}}</span><br>
Negative number: <span>{{-val | number:4}}</span>
</div>
</body>
</html>
Protractor.js
it('should format numbers', function() {
expect(element(by.id('number-default')).getText()).toBe('1,234.568');
expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
});
it('should update', function() {
element(by.model('val')).clear();
element(by.model('val')).sendKeys('3374.333');
expect(element(by.id('number-default')).getText()).toBe('3,374.333');
expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
});
2 Comments
Ben Kolya Mansley
Please provide some explanation with your answer - otherwise this should be a comment
JDP
sure, will take care for this
toLocaleString()- docs2,345, value would be the same), but filter the,and eventuelly convert to number when you actually use it, much simpler