<input type="text" OnlyDecimal="true" > -- Html Code here
First Create Directive.ts File and Put Code Inside
*************************onlynumberwithdecimal.directive.ts***************************
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[OnlyDecimal]'
})
export class OnlyDecimal {
constructor(private el: ElementRef) { }
@Input() OnlyDecimal: boolean;
@HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent>event;
if (e.which == 13) {
e.preventDefault();
var $next = $('[tabIndex=' + (+ parseInt(e.target['tabIndex']) + 1) + ']');
if (!$next.length) {
$next = $('[tabIndex=1]');
}
$next.focus();
}
else if (this.OnlyDecimal) {
var input = <HTMLInputElement>event.srcElement;
var inputVal = input.value;
if (event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) {
return true;
}
else if (inputVal.indexOf('.') > -1 && e.key == ".") {
e.preventDefault();
}
else if (parseFloat(inputVal) * 100 % 1 > 0) {
e.preventDefault();
}
else if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
else if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
}
}
/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
0 Comments