I have a number of input boxes on a html page. I want to restrict the user from entering any numbers after 2 decimals.
Currently try to apply html 5 input Step="0.00" but doesn't work.
Any typescript solution is also ok
I got the solution using @pipe
import { Directive,Input,Inject, HostListener, ElementRef, OnInit } from "@angular/core";
const PADDING = "000000";
@Pipe({ name: "CurrencyPipe" })
export class CurrencyPipe implements PipeTransform {
transform(value: any, args: string[]): any {
var clean = value.replace(/[^-0-9\.]/g, '');
var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
if (negativeCheck[1] != undefined) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean = negativeCheck[0] + '-' + negativeCheck[1];
if (negativeCheck[0].length > 0) {
clean = negativeCheck[0];
}
}
if (decimalCheck[1] != undefined) {
decimalCheck[1] = decimalCheck[1].slice(0, 2);
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
return clean;
}
parse(value: string, fractionSize: number = 2): string {
var clean = value.replace(/[^-0-9\.]/g, '');
var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
if (negativeCheck[1] != undefined) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean = negativeCheck[0] + '-' + negativeCheck[1];
if (negativeCheck[0].length > 0) {
clean = negativeCheck[0];
}
}
if (decimalCheck[1] != undefined) {
decimalCheck[1] = decimalCheck[1].slice(0, 2);
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
return clean;
}
}
And Pipe Extends in my directive.
import { Directive, Input, Inject, HostListener, OnChanges, ElementRef, Renderer, AfterViewInit, OnInit } from "@angular/core";
import { CurrencyPipe } from '../../shared/pipe/orderby';
@Directive({ selector: "[CurrencyFormatter]" })
export class CurrencyFormatterDirective {
private el: HTMLInputElement;
constructor(
private elementRef: ElementRef,
private currencyPipe: CurrencyPipe
) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
this.el.value = this.currencyPipe.parse(this.el.value);
}
@HostListener("focus", ["$event.target.value"])
onFocus(value) {
this.el.value = this.currencyPipe.parse(value); // opossite of transform
}
@HostListener("blur", ["$event.target.value"])
onBlur(value) {
this.el.value = this.currencyPipe.parse(value);
}
@HostListener("keyup", ["$event.target.value"])
onKeyUp(value) {
this.el.value = this.currencyPipe.parse(value);
}
}
Import Directive on your component
import { CurrencyFormatterDirective } from '../../shared/directive/showOnRowHover';
import { CurrencyPipe } from '../../shared/pipe/orderby';
providers: [CurrencyPipe,
CurrencyFormatterDirective]
And Directive on your html Input
<input type="text" [(ngModel)]="invoiceDetail.InvoiceAmount" class="form-control" placeholder="Enter invoice amount"
CurrencyFormatter>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With