'Angular directive - Only digits and 2 decimals with comma separated
I need to allow to only write in an input numbers and optionally 1 comma and 2 decimals.
Example of right inputs:
123
123,22
I've tried this directive I found online but it's allowing me to enter these characters: `, ´, +
Directive code:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimalNumberDirective {
// Allow decimal numbers and negative values
private regex: RegExp = new RegExp(/^\d*\,?\d{0,2}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
constructor(private el: ElementRef) {
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
console.log(this.el.nativeElement.value);
// Allow Backspace, tab, end, and home keys
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
let current: string = this.el.nativeElement.value;
const position = this.el.nativeElement.selectionStart;
const next: string = [current.slice(0, position), event.key == 'Decimal' ? ',' : event.key, current.slice(position)].join('');
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
What's wrong with this code?
Thanks
Solution 1:[1]
JUST CHANGE YOUR INPUT TYPE NUMBER TO TEXT
pipe:
import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[appDecimalAmount]'
})
export class DecimalAmountDirective {
private regex: RegExp = new RegExp(/^\d*\,?\d{0,2}$/g);
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
constructor(private el: ElementRef) { }
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
const current: string = this.el.nativeElement.value;
const next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
HTML
<label> Cost (€) <sup class="text-danger">*</sup></label>
<input type="text" formControlName="predictShippingCost" min="0" appDecimalAmount>
``
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Manish Patidar |