Last active
April 27, 2020 06:35
-
-
Save sankarseran/327186b1a03db1322f00b768abd75d1e to your computer and use it in GitHub Desktop.
This used prevent the typing in input based on key code. In this directive we can give two type number, alphanumeric and alphabets.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; | |
@Directive({ | |
// tslint:disable-next-line:directive-selector | |
selector: '[keyPrevent]' | |
}) | |
export class KeyPreventDirective { | |
constructor(private el: ElementRef) { } | |
@Input() OnlyNumber: boolean; | |
@Input() Alphabets: boolean; | |
@Input() Alphanumeric: boolean; | |
@Input() OnlyNumberWihtoutDecimel: boolean; | |
@HostListener('keydown', ['$event']) onKeyDown(event) { | |
const e = <KeyboardEvent>event; | |
if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 || | |
// Allow: Ctrl+A | |
(e.keyCode === 65 && (e.ctrlKey || e.metaKey)) || | |
// Allow: Ctrl+C | |
(e.keyCode === 67 && (e.ctrlKey || e.metaKey)) || | |
// Allow: Ctrl+V | |
// (e.keyCode === 86 && (e.ctrlKey || e.metaKey)) || | |
// Allow: Ctrl+X | |
(e.keyCode === 88 && (e.ctrlKey || e.metaKey)) || | |
// Allow: home, end, left, right | |
(e.keyCode >= 35 && e.keyCode <= 39)) { | |
// let it happen, don't do anything | |
return; | |
} | |
if (this.OnlyNumber) { | |
// Ensure that it is a number and stop the keypress | |
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { | |
e.preventDefault(); | |
} | |
} else if (this.Alphabets) { | |
// Ensure that it is a alphabets and stop the keypress | |
if (e.keyCode < 65 || e.keyCode > 90) { | |
e.preventDefault(); | |
} | |
} else if (this.Alphanumeric) { | |
// Ensure that it is a number and stop the keypress | |
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105) && | |
(e.keyCode < 65 || e.keyCode > 90)) { | |
e.preventDefault(); | |
} | |
} | |
} | |
@HostListener('keypress', ['$event']) onKeyPress(event) { | |
if (this.OnlyNumberWihtoutDecimel) { | |
const key = event.which; | |
if (!( key >= 48 && key <= 57) ) { | |
event.preventDefault(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment