Counting the sum live - custom currency format (comma as decimal separator)Angular 2 change event on every keypressAngularjs2 and polymer-input form binding not working as expectedAngular2 Currency Pipe change decimal separatorSeparate numeric and decimal in Angularjs2Angular currency input with decimal placeholderCurrency pipe wrong formatAngular currency pipe no decimal valuengx-mask to accept negative numbersAngular 6 : decimal pipe for comma separation not workingAngular 6 currency format without decimal point with INR symbolngx-numeric-textbox with comma as decimal separator
Disable all sound permanently
Can the Fixed-Term Parliaments Act be bypassed by a simple bill?
MaxCounters solution in C# from Codility
Principled construction of the quaternions
If I travelled back in time to invest in X company to make a fortune, roughly what is the probability that it would fail?
Knights and Knaves: What does C say?
What does "execute a hard copy" mean?
French license plates
Realistically, how much do you need to start investing?
Would a horse be sufficient buffer to prevent injury when falling from a great height?
Giving a good fancy look to a simple table
Looking for circuit board material that can be dissolved
A word that refers to saying something in an attempt to anger or embarrass someone into doing something that they don’t want to do?
Replace zeros in a list with last nonzero value
Did the Soviet army intentionally send troops (e.g. penal battalions) running over minefields?
How do we decide/plan an SLA for an NP-hard optimization process running in production?
Can a passenger predict that an airline or a tour operator is about to go bankrupt?
Should I be an author on another PhD student's paper if I went to their meetings and gave advice?
Duck, duck, gone!
Parent asking for money after moving out
Everyone Gets a Window Seat
How is this situation not a checkmate?
Why the first octet of a MAC address always end with a binary 0?
Are there types of animals that can't make the trip to space? (physiologically)
Counting the sum live - custom currency format (comma as decimal separator)
Angular 2 change event on every keypressAngularjs2 and polymer-input form binding not working as expectedAngular2 Currency Pipe change decimal separatorSeparate numeric and decimal in Angularjs2Angular currency input with decimal placeholderCurrency pipe wrong formatAngular currency pipe no decimal valuengx-mask to accept negative numbersAngular 6 : decimal pipe for comma separation not workingAngular 6 currency format without decimal point with INR symbolngx-numeric-textbox with comma as decimal separator
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;
I want to have input for currency.
Requirements:
- decimal seperator[comma (,)]
- fraction size always 2 digits
So displayed value in input textbox is 100,55
. The value in the model is: 100.55
.
I have this and seems to work correctly. I also want to display the current sum.
Currently, the value of the sum is updated when I leave input.
For example:
- input_1:
100.50
- input_2:
100.50
(When the value is changed to 100, the sum should immediately be updated, without leaving input) - Sum:
201
Code:
https://stackblitz.com/edit/angular-1qzpaz?embed=1&file=src/app/app.component.html
I don't want to use ngx-currency
mask, because in ng-currency
mask values are changed. For example user type: 54 --> will be changed to: 0,54. Should be 54.
import Component, OnInit from '@angular/core';
import User, UserService from './user.service';
@Component(
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [UserService]
)
export class AppComponent implements OnInit
title = 'Users list';
users: User[];
constructor(private userService: UserService)
ngOnInit(): void
this.userService.getUsers().then(users => this.users = users);
getSum(users: any[]): number
let sum: number = 0.00;
users.forEach(u=>
console.log(u.money);
if(u.money)
let tempMoney = Number(u.money.toString().replace(',', '.'));
sum += tempMoney;
);
return sum;
<h1>
title
</h1>
<li *ngFor="let user of users">
<span >user.id</span> user.name
<input type="text" appCurrencyMask [fractionSize]="2"
name="money"
[(ngModel)]="user.money"/>
Model: user.money
</li>
<br/>Total: getSum(users)
import AfterViewInit, Directive, ElementRef, forwardRef, HostListener, Input, Renderer2 from '@angular/core';
import ControlValueAccessor, NG_VALUE_ACCESSOR from '@angular/forms';
import CurrencyMaskService from "./currency-mask.service";
const noop = () =>
;
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any =
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CurrencyMaskDirective),
multi: true
;
/*
* Custom Directive for Currency Mask
* The main requirements that drove the creation of this custom directive currency mask are:
* 1. Currency Mask had to be easy to implement across application. Directive control was used to accomplish that and everything is under one Module that can be easily imported.
* 2. Formatted value should be composed of: US dollar currency symbol '$' + value + 2 decimal point precision.
* 3. When user focus on the input, it should remove all formatting and only keep the decimal amount with the precision. If the input is blank and:
* a. The user types "100" then unfocus, it should display $100.00
* b. The user types "100.10" then unfocus, it should display $100.10
* c. The user types ".25" then unfocus, it should display $0.25
* 4. User shouldn't be able to type anything that isn't numbers or decimal separator "."
* 5. Optional parameter for allowing negative numbers added. On Edit mode the the indicative of negative number is the minus "-" sign, but when
* formatted we surround the value with parenthesis. So on input -300.12 will display as ($300.12).
*/
@Directive(
selector: '[appCurrencyMask]',
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
)
export class CurrencyMaskDirective implements AfterViewInit, ControlValueAccessor
private el: HTMLInputElement;
private innerValue: any;
@Input('allowNegative')
allowNegative: boolean; // Optional Parameter to allow for negative number interaction
@Input('fractionSize')
fractionSize: number;
constructor(private elementRef: ElementRef, private currencyMaskService: CurrencyMaskService, private renderer: Renderer2)
this.el = elementRef.nativeElement;
// Placeholders for the callbacks which are later providesd
// by the Control Value Accessor
private onTouchedCallback: () => void = noop;
private onChangeCallback: (a: any) => void = noop;
// set getter
get value(): any
return this.innerValue;
// set accessor including call the onchange callback
set value(v: any)
if (v !== this.innerValue)
this.innerValue = v;
this.onChangeCallback(v);
// From ControlValueAccessor interface
writeValue(value: any)
if (value !== this.innerValue)
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
if (value)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', value);
this.innerValue = value;
// From ControlValueAccessor interface
registerOnChange(fn: any)
this.onChangeCallback = fn;
// From ControlValueAccessor interface
registerOnTouched(fn: any)
this.onTouchedCallback = fn;
ngAfterViewInit()
this.el.style.textAlign = 'right';
// On Focus remove all non-digit or decimal separator values
@HostListener('focus', ['$event.target.value'])
onfocus(value)
this.el.value = this.currencyMaskService.parse(value, this.allowNegative, this.fractionSize);
// On Blue remove all symbols except last . and set to currency format
@HostListener('blur', ['$event.target.value'])
onBlur(value)
this.onTouchedCallback();
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
this.innerValue = this.currencyMaskService.parse(this.el.value, this.allowNegative, this.fractionSize);
this.onChangeCallback(this.innerValue);
if (this.innerValue)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', this.innerValue);
// On Change remove all symbols except last . and set to currency format
@HostListener('change', ['$event.target.value'])
onChange(value)
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
this.innerValue = this.currencyMaskService.parse(this.el.value, this.allowNegative, this.fractionSize);
this.onChangeCallback(this.innerValue);
if (this.innerValue)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', this.innerValue);
// Prevent user to enter anything but digits and decimal separator
@HostListener('keypress', ['$event'])
onKeyPress(event) key > 57))
event.preventDefault();
import Injectable from '@angular/core';
const padding = "000000";
@Injectable()
export class CurrencyMaskService
private prefix: string;
private thousandsSeparator: string;
private decimalSeparator: string = ',';
constructor()
this.prefix = '';
this.thousandsSeparator = '.';
this.decimalSeparator = ','
transform(value: string, allowNegative = false, fractionSize: number) value === '')
return null;
if (allowNegative) value.startsWith('-')) $ else
value = value.replace(/(
value = value.toString().replace('.', ',');
let [integer, fraction = ''] = (value
parse(value: string, allowNegative = false, fractionSize: number)
angular
add a comment
|
I want to have input for currency.
Requirements:
- decimal seperator[comma (,)]
- fraction size always 2 digits
So displayed value in input textbox is 100,55
. The value in the model is: 100.55
.
I have this and seems to work correctly. I also want to display the current sum.
Currently, the value of the sum is updated when I leave input.
For example:
- input_1:
100.50
- input_2:
100.50
(When the value is changed to 100, the sum should immediately be updated, without leaving input) - Sum:
201
Code:
https://stackblitz.com/edit/angular-1qzpaz?embed=1&file=src/app/app.component.html
I don't want to use ngx-currency
mask, because in ng-currency
mask values are changed. For example user type: 54 --> will be changed to: 0,54. Should be 54.
import Component, OnInit from '@angular/core';
import User, UserService from './user.service';
@Component(
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [UserService]
)
export class AppComponent implements OnInit
title = 'Users list';
users: User[];
constructor(private userService: UserService)
ngOnInit(): void
this.userService.getUsers().then(users => this.users = users);
getSum(users: any[]): number
let sum: number = 0.00;
users.forEach(u=>
console.log(u.money);
if(u.money)
let tempMoney = Number(u.money.toString().replace(',', '.'));
sum += tempMoney;
);
return sum;
<h1>
title
</h1>
<li *ngFor="let user of users">
<span >user.id</span> user.name
<input type="text" appCurrencyMask [fractionSize]="2"
name="money"
[(ngModel)]="user.money"/>
Model: user.money
</li>
<br/>Total: getSum(users)
import AfterViewInit, Directive, ElementRef, forwardRef, HostListener, Input, Renderer2 from '@angular/core';
import ControlValueAccessor, NG_VALUE_ACCESSOR from '@angular/forms';
import CurrencyMaskService from "./currency-mask.service";
const noop = () =>
;
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any =
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CurrencyMaskDirective),
multi: true
;
/*
* Custom Directive for Currency Mask
* The main requirements that drove the creation of this custom directive currency mask are:
* 1. Currency Mask had to be easy to implement across application. Directive control was used to accomplish that and everything is under one Module that can be easily imported.
* 2. Formatted value should be composed of: US dollar currency symbol '$' + value + 2 decimal point precision.
* 3. When user focus on the input, it should remove all formatting and only keep the decimal amount with the precision. If the input is blank and:
* a. The user types "100" then unfocus, it should display $100.00
* b. The user types "100.10" then unfocus, it should display $100.10
* c. The user types ".25" then unfocus, it should display $0.25
* 4. User shouldn't be able to type anything that isn't numbers or decimal separator "."
* 5. Optional parameter for allowing negative numbers added. On Edit mode the the indicative of negative number is the minus "-" sign, but when
* formatted we surround the value with parenthesis. So on input -300.12 will display as ($300.12).
*/
@Directive(
selector: '[appCurrencyMask]',
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
)
export class CurrencyMaskDirective implements AfterViewInit, ControlValueAccessor
private el: HTMLInputElement;
private innerValue: any;
@Input('allowNegative')
allowNegative: boolean; // Optional Parameter to allow for negative number interaction
@Input('fractionSize')
fractionSize: number;
constructor(private elementRef: ElementRef, private currencyMaskService: CurrencyMaskService, private renderer: Renderer2)
this.el = elementRef.nativeElement;
// Placeholders for the callbacks which are later providesd
// by the Control Value Accessor
private onTouchedCallback: () => void = noop;
private onChangeCallback: (a: any) => void = noop;
// set getter
get value(): any
return this.innerValue;
// set accessor including call the onchange callback
set value(v: any)
if (v !== this.innerValue)
this.innerValue = v;
this.onChangeCallback(v);
// From ControlValueAccessor interface
writeValue(value: any)
if (value !== this.innerValue)
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
if (value)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', value);
this.innerValue = value;
// From ControlValueAccessor interface
registerOnChange(fn: any)
this.onChangeCallback = fn;
// From ControlValueAccessor interface
registerOnTouched(fn: any)
this.onTouchedCallback = fn;
ngAfterViewInit()
this.el.style.textAlign = 'right';
// On Focus remove all non-digit or decimal separator values
@HostListener('focus', ['$event.target.value'])
onfocus(value)
this.el.value = this.currencyMaskService.parse(value, this.allowNegative, this.fractionSize);
// On Blue remove all symbols except last . and set to currency format
@HostListener('blur', ['$event.target.value'])
onBlur(value)
this.onTouchedCallback();
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
this.innerValue = this.currencyMaskService.parse(this.el.value, this.allowNegative, this.fractionSize);
this.onChangeCallback(this.innerValue);
if (this.innerValue)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', this.innerValue);
// On Change remove all symbols except last . and set to currency format
@HostListener('change', ['$event.target.value'])
onChange(value)
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
this.innerValue = this.currencyMaskService.parse(this.el.value, this.allowNegative, this.fractionSize);
this.onChangeCallback(this.innerValue);
if (this.innerValue)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', this.innerValue);
// Prevent user to enter anything but digits and decimal separator
@HostListener('keypress', ['$event'])
onKeyPress(event) key > 57))
event.preventDefault();
import Injectable from '@angular/core';
const padding = "000000";
@Injectable()
export class CurrencyMaskService
private prefix: string;
private thousandsSeparator: string;
private decimalSeparator: string = ',';
constructor()
this.prefix = '';
this.thousandsSeparator = '.';
this.decimalSeparator = ','
transform(value: string, allowNegative = false, fractionSize: number) value === '')
return null;
if (allowNegative) value.startsWith('-')) $ else
value = value.replace(/(
value = value.toString().replace('.', ',');
let [integer, fraction = ''] = (value
parse(value: string, allowNegative = false, fractionSize: number)
angular
this post may help: stackoverflow.com/questions/35359358/…
– davidr
Mar 28 at 21:11
add a comment
|
I want to have input for currency.
Requirements:
- decimal seperator[comma (,)]
- fraction size always 2 digits
So displayed value in input textbox is 100,55
. The value in the model is: 100.55
.
I have this and seems to work correctly. I also want to display the current sum.
Currently, the value of the sum is updated when I leave input.
For example:
- input_1:
100.50
- input_2:
100.50
(When the value is changed to 100, the sum should immediately be updated, without leaving input) - Sum:
201
Code:
https://stackblitz.com/edit/angular-1qzpaz?embed=1&file=src/app/app.component.html
I don't want to use ngx-currency
mask, because in ng-currency
mask values are changed. For example user type: 54 --> will be changed to: 0,54. Should be 54.
import Component, OnInit from '@angular/core';
import User, UserService from './user.service';
@Component(
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [UserService]
)
export class AppComponent implements OnInit
title = 'Users list';
users: User[];
constructor(private userService: UserService)
ngOnInit(): void
this.userService.getUsers().then(users => this.users = users);
getSum(users: any[]): number
let sum: number = 0.00;
users.forEach(u=>
console.log(u.money);
if(u.money)
let tempMoney = Number(u.money.toString().replace(',', '.'));
sum += tempMoney;
);
return sum;
<h1>
title
</h1>
<li *ngFor="let user of users">
<span >user.id</span> user.name
<input type="text" appCurrencyMask [fractionSize]="2"
name="money"
[(ngModel)]="user.money"/>
Model: user.money
</li>
<br/>Total: getSum(users)
import AfterViewInit, Directive, ElementRef, forwardRef, HostListener, Input, Renderer2 from '@angular/core';
import ControlValueAccessor, NG_VALUE_ACCESSOR from '@angular/forms';
import CurrencyMaskService from "./currency-mask.service";
const noop = () =>
;
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any =
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CurrencyMaskDirective),
multi: true
;
/*
* Custom Directive for Currency Mask
* The main requirements that drove the creation of this custom directive currency mask are:
* 1. Currency Mask had to be easy to implement across application. Directive control was used to accomplish that and everything is under one Module that can be easily imported.
* 2. Formatted value should be composed of: US dollar currency symbol '$' + value + 2 decimal point precision.
* 3. When user focus on the input, it should remove all formatting and only keep the decimal amount with the precision. If the input is blank and:
* a. The user types "100" then unfocus, it should display $100.00
* b. The user types "100.10" then unfocus, it should display $100.10
* c. The user types ".25" then unfocus, it should display $0.25
* 4. User shouldn't be able to type anything that isn't numbers or decimal separator "."
* 5. Optional parameter for allowing negative numbers added. On Edit mode the the indicative of negative number is the minus "-" sign, but when
* formatted we surround the value with parenthesis. So on input -300.12 will display as ($300.12).
*/
@Directive(
selector: '[appCurrencyMask]',
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
)
export class CurrencyMaskDirective implements AfterViewInit, ControlValueAccessor
private el: HTMLInputElement;
private innerValue: any;
@Input('allowNegative')
allowNegative: boolean; // Optional Parameter to allow for negative number interaction
@Input('fractionSize')
fractionSize: number;
constructor(private elementRef: ElementRef, private currencyMaskService: CurrencyMaskService, private renderer: Renderer2)
this.el = elementRef.nativeElement;
// Placeholders for the callbacks which are later providesd
// by the Control Value Accessor
private onTouchedCallback: () => void = noop;
private onChangeCallback: (a: any) => void = noop;
// set getter
get value(): any
return this.innerValue;
// set accessor including call the onchange callback
set value(v: any)
if (v !== this.innerValue)
this.innerValue = v;
this.onChangeCallback(v);
// From ControlValueAccessor interface
writeValue(value: any)
if (value !== this.innerValue)
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
if (value)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', value);
this.innerValue = value;
// From ControlValueAccessor interface
registerOnChange(fn: any)
this.onChangeCallback = fn;
// From ControlValueAccessor interface
registerOnTouched(fn: any)
this.onTouchedCallback = fn;
ngAfterViewInit()
this.el.style.textAlign = 'right';
// On Focus remove all non-digit or decimal separator values
@HostListener('focus', ['$event.target.value'])
onfocus(value)
this.el.value = this.currencyMaskService.parse(value, this.allowNegative, this.fractionSize);
// On Blue remove all symbols except last . and set to currency format
@HostListener('blur', ['$event.target.value'])
onBlur(value)
this.onTouchedCallback();
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
this.innerValue = this.currencyMaskService.parse(this.el.value, this.allowNegative, this.fractionSize);
this.onChangeCallback(this.innerValue);
if (this.innerValue)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', this.innerValue);
// On Change remove all symbols except last . and set to currency format
@HostListener('change', ['$event.target.value'])
onChange(value)
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
this.innerValue = this.currencyMaskService.parse(this.el.value, this.allowNegative, this.fractionSize);
this.onChangeCallback(this.innerValue);
if (this.innerValue)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', this.innerValue);
// Prevent user to enter anything but digits and decimal separator
@HostListener('keypress', ['$event'])
onKeyPress(event) key > 57))
event.preventDefault();
import Injectable from '@angular/core';
const padding = "000000";
@Injectable()
export class CurrencyMaskService
private prefix: string;
private thousandsSeparator: string;
private decimalSeparator: string = ',';
constructor()
this.prefix = '';
this.thousandsSeparator = '.';
this.decimalSeparator = ','
transform(value: string, allowNegative = false, fractionSize: number) value === '')
return null;
if (allowNegative) value.startsWith('-')) $ else
value = value.replace(/(
value = value.toString().replace('.', ',');
let [integer, fraction = ''] = (value
parse(value: string, allowNegative = false, fractionSize: number)
angular
I want to have input for currency.
Requirements:
- decimal seperator[comma (,)]
- fraction size always 2 digits
So displayed value in input textbox is 100,55
. The value in the model is: 100.55
.
I have this and seems to work correctly. I also want to display the current sum.
Currently, the value of the sum is updated when I leave input.
For example:
- input_1:
100.50
- input_2:
100.50
(When the value is changed to 100, the sum should immediately be updated, without leaving input) - Sum:
201
Code:
https://stackblitz.com/edit/angular-1qzpaz?embed=1&file=src/app/app.component.html
I don't want to use ngx-currency
mask, because in ng-currency
mask values are changed. For example user type: 54 --> will be changed to: 0,54. Should be 54.
import Component, OnInit from '@angular/core';
import User, UserService from './user.service';
@Component(
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [UserService]
)
export class AppComponent implements OnInit
title = 'Users list';
users: User[];
constructor(private userService: UserService)
ngOnInit(): void
this.userService.getUsers().then(users => this.users = users);
getSum(users: any[]): number
let sum: number = 0.00;
users.forEach(u=>
console.log(u.money);
if(u.money)
let tempMoney = Number(u.money.toString().replace(',', '.'));
sum += tempMoney;
);
return sum;
<h1>
title
</h1>
<li *ngFor="let user of users">
<span >user.id</span> user.name
<input type="text" appCurrencyMask [fractionSize]="2"
name="money"
[(ngModel)]="user.money"/>
Model: user.money
</li>
<br/>Total: getSum(users)
import AfterViewInit, Directive, ElementRef, forwardRef, HostListener, Input, Renderer2 from '@angular/core';
import ControlValueAccessor, NG_VALUE_ACCESSOR from '@angular/forms';
import CurrencyMaskService from "./currency-mask.service";
const noop = () =>
;
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any =
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CurrencyMaskDirective),
multi: true
;
/*
* Custom Directive for Currency Mask
* The main requirements that drove the creation of this custom directive currency mask are:
* 1. Currency Mask had to be easy to implement across application. Directive control was used to accomplish that and everything is under one Module that can be easily imported.
* 2. Formatted value should be composed of: US dollar currency symbol '$' + value + 2 decimal point precision.
* 3. When user focus on the input, it should remove all formatting and only keep the decimal amount with the precision. If the input is blank and:
* a. The user types "100" then unfocus, it should display $100.00
* b. The user types "100.10" then unfocus, it should display $100.10
* c. The user types ".25" then unfocus, it should display $0.25
* 4. User shouldn't be able to type anything that isn't numbers or decimal separator "."
* 5. Optional parameter for allowing negative numbers added. On Edit mode the the indicative of negative number is the minus "-" sign, but when
* formatted we surround the value with parenthesis. So on input -300.12 will display as ($300.12).
*/
@Directive(
selector: '[appCurrencyMask]',
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
)
export class CurrencyMaskDirective implements AfterViewInit, ControlValueAccessor
private el: HTMLInputElement;
private innerValue: any;
@Input('allowNegative')
allowNegative: boolean; // Optional Parameter to allow for negative number interaction
@Input('fractionSize')
fractionSize: number;
constructor(private elementRef: ElementRef, private currencyMaskService: CurrencyMaskService, private renderer: Renderer2)
this.el = elementRef.nativeElement;
// Placeholders for the callbacks which are later providesd
// by the Control Value Accessor
private onTouchedCallback: () => void = noop;
private onChangeCallback: (a: any) => void = noop;
// set getter
get value(): any
return this.innerValue;
// set accessor including call the onchange callback
set value(v: any)
if (v !== this.innerValue)
this.innerValue = v;
this.onChangeCallback(v);
// From ControlValueAccessor interface
writeValue(value: any)
if (value !== this.innerValue)
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
if (value)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', value);
this.innerValue = value;
// From ControlValueAccessor interface
registerOnChange(fn: any)
this.onChangeCallback = fn;
// From ControlValueAccessor interface
registerOnTouched(fn: any)
this.onTouchedCallback = fn;
ngAfterViewInit()
this.el.style.textAlign = 'right';
// On Focus remove all non-digit or decimal separator values
@HostListener('focus', ['$event.target.value'])
onfocus(value)
this.el.value = this.currencyMaskService.parse(value, this.allowNegative, this.fractionSize);
// On Blue remove all symbols except last . and set to currency format
@HostListener('blur', ['$event.target.value'])
onBlur(value)
this.onTouchedCallback();
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
this.innerValue = this.currencyMaskService.parse(this.el.value, this.allowNegative, this.fractionSize);
this.onChangeCallback(this.innerValue);
if (this.innerValue)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', this.innerValue);
// On Change remove all symbols except last . and set to currency format
@HostListener('change', ['$event.target.value'])
onChange(value)
this.el.value = this.currencyMaskService.transform(value, this.allowNegative, this.fractionSize);
this.innerValue = this.currencyMaskService.parse(this.el.value, this.allowNegative, this.fractionSize);
this.onChangeCallback(this.innerValue);
if (this.innerValue)
this.renderer.setAttribute(this.elementRef.nativeElement, 'value', this.innerValue);
// Prevent user to enter anything but digits and decimal separator
@HostListener('keypress', ['$event'])
onKeyPress(event) key > 57))
event.preventDefault();
import Injectable from '@angular/core';
const padding = "000000";
@Injectable()
export class CurrencyMaskService
private prefix: string;
private thousandsSeparator: string;
private decimalSeparator: string = ',';
constructor()
this.prefix = '';
this.thousandsSeparator = '.';
this.decimalSeparator = ','
transform(value: string, allowNegative = false, fractionSize: number) value === '')
return null;
if (allowNegative) value.startsWith('-')) $ else
value = value.replace(/(
value = value.toString().replace('.', ',');
let [integer, fraction = ''] = (value
parse(value: string, allowNegative = false, fractionSize: number)
angular
angular
edited Mar 28 at 22:38
Faruq
7425 silver badges19 bronze badges
7425 silver badges19 bronze badges
asked Mar 28 at 20:47
mgc.jdevmgc.jdev
1
1
this post may help: stackoverflow.com/questions/35359358/…
– davidr
Mar 28 at 21:11
add a comment
|
this post may help: stackoverflow.com/questions/35359358/…
– davidr
Mar 28 at 21:11
this post may help: stackoverflow.com/questions/35359358/…
– davidr
Mar 28 at 21:11
this post may help: stackoverflow.com/questions/35359358/…
– davidr
Mar 28 at 21:11
add a comment
|
1 Answer
1
active
oldest
votes
No. I think that problem is in directive with host listeners.
Problem is here providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] when I commented this. It works, but I need it.
– mgc.jdev
Mar 29 at 12:13
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55406617%2fcounting-the-sum-live-custom-currency-format-comma-as-decimal-separator%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
No. I think that problem is in directive with host listeners.
Problem is here providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] when I commented this. It works, but I need it.
– mgc.jdev
Mar 29 at 12:13
add a comment
|
No. I think that problem is in directive with host listeners.
Problem is here providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] when I commented this. It works, but I need it.
– mgc.jdev
Mar 29 at 12:13
add a comment
|
No. I think that problem is in directive with host listeners.
No. I think that problem is in directive with host listeners.
answered Mar 29 at 8:45
mgc.jdevmgc.jdev
1
1
Problem is here providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] when I commented this. It works, but I need it.
– mgc.jdev
Mar 29 at 12:13
add a comment
|
Problem is here providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] when I commented this. It works, but I need it.
– mgc.jdev
Mar 29 at 12:13
Problem is here providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] when I commented this. It works, but I need it.
– mgc.jdev
Mar 29 at 12:13
Problem is here providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR] when I commented this. It works, but I need it.
– mgc.jdev
Mar 29 at 12:13
add a comment
|
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55406617%2fcounting-the-sum-live-custom-currency-format-comma-as-decimal-separator%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
this post may help: stackoverflow.com/questions/35359358/…
– davidr
Mar 28 at 21:11