对于某些输入字段,我正在使用角度6,并且编写了一条指令以将输入限制为仅数字。指令看起来像这样
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[NumbersOnly]'
})
export class NumbersOnlyDirective {
// Allow decimal numbers and negative values
private regex: RegExp = new RegExp(/^-?[0-9]+(\.[0-9]*){0,1}$/g);
// Allow key codes for special events. Reflect :
// Backspace, tab, end, home
private specialKeys: Array<string> = [ 'ArrowLeft', 'ArrowRight','Backspace', 'Tab', 'End', 'Home' ];
constructor(private el: ElementRef) {
}
@HostListener('keydown', [ '$event' ])
onKeyDown(event: KeyboardEvent) {
// Allow Backspace, tab, end, and home keys
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();
}
}
}
在我有输入字段的任何地方,我都使用以下指令
<input [(ngModel)]="sendLinkMobile" NumbersOnly type="text" id="mobile-num" class="form-control m-no" placeholder="Mobile Number" requried minlength="10" maxlength="10" aria-label="Recipient's username" aria-describedby="basic-addon2">
该代码可在所有最新的浏览器,手机,标签页中完美运行。但是,在chrome 49.xx及以下版本上使用时,输入字段没有任何值。谁能帮助我解决问题所在?
谢谢。
答案 0 :(得分:1)
使用it指令并将其检出。我认为它适用于chrome 49.xx
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[OnlyNumber]'
})
export class Onlynumber {
constructor(private el: ElementRef) { }
@Input() OnlyNumber: boolean;
@HostListener('keydown', ['$event']) onKeyDown(event) {
let e = <KeyboardEvent> event;
if (this.OnlyNumber) {
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;
}
// 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();
}
}
}
}
HTML:
<input OnlyNumber="true" type="text" #numberModel="ngModel" [(ngModel)]="numberModel" name="numberModel" />