Skip to content

Instantly share code, notes, and snippets.

@ahmeti
Last active May 7, 2024 14:54
Show Gist options
  • Save ahmeti/5ca97ec41f6a48ef699ee6606560d1f7 to your computer and use it in GitHub Desktop.
Save ahmeti/5ca97ec41f6a48ef699ee6606560d1f7 to your computer and use it in GitHub Desktop.
Angular 5 - Only Number Input, Only Number Decimal

Angular 5,6,7,8,9 - Only Number Input, Only Decimal Input

v1 Online Demo: https://codesandbox.io/s/v1-angular-numeric-ljwlb

v1 Gist : https://gist.github.com/ahmeti/5ca97ec41f6a48ef699ee6606560d1f7/e36956cc355ad1bad6898e9eede5d7a9219947e8

v2 Online Demo: https://codesandbox.io/s/v2-angular-numeric-3w2wr

Allow Only Numbers (Without Decimal)

<input numeric type="text">

Allow Numbers & Only Two Decimals [0-9] (With Decimal Limit)

<input numeric decimals="2" type="text">
// Version 2

import {
    Directive,
    ElementRef,
    HostListener,
    Input
} from "@angular/core";

@Directive({
    selector: "[numeric]"
})
export class NumericDirective {
    @Input("decimals") decimals: int = 0;

    private check(value: string) {
        if (this.decimals <= 0) {
            return String(value).match(new RegExp(/^\d+$/));
        } else {
            var regExpString =
                "^\\s*((\\d+(\\.\\d{0," +
                this.decimals +
                "})?)|((\\d*(\\.\\d{1," +
                this.decimals +
                "}))))\\s*$";
            return String(value).match(new RegExp(regExpString));
        }
    }

    private run(oldValue) {
        setTimeout(() => {
            let currentValue: string = this.el.nativeElement.value;
            if (currentValue !== '' && !this.check(currentValue)) {
                this.el.nativeElement.value = oldValue;
            }
        });
    }

    constructor(private el: ElementRef) {}

    @HostListener("keydown", ["$event"])
    onKeyDown(event: KeyboardEvent) {
        this.run(this.el.nativeElement.value);
    }

    @HostListener("paste", ["$event"])
    onPaste(event: ClipboardEvent) {
        this.run(this.el.nativeElement.value);
    }

}
@LSzelecsenyi
Copy link

is there any new update for 13

it works with angular v14

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment