angular2限制鍵盤響應,如:只接收數字鍵盤輸入
阿新 • • 發佈:2019-01-28
一、type值為number
<input type="number" />
二、通過ng2雙向繫結與事件方式實現
1、html程式碼:
<input type="text" #inputVars (keyup)="onKeyPress(inputVars.value)" (keydown)="onKeyDown($event)" [(ngModel)]="inputValue"/>
2、angular程式碼片段
inputValue: any; onKeyPress(value: any) { if (value === '' || isUndefined(value) || value.length=== 0) { this.inputValue = ''; return; } const str: any[] = value.split('.'); if (str && str.length === 2) { this.dotFlag = true; if (str[1] === '' && !isNaN(parseInt(str[0]))) { this.inputValue = value; return; } else { this.inputValue = checkIsFloat(value); return; } } else { this.dotFlag = false; this.inputValue = checkIsFloat(value); return; } function checkIsFloat(value: any) { const newValue = parseFloat(value); if (isNaN(newValue)) { return ''; } return newValue; } } private dotFlag: boolean = false; onKeyDown(event: any) { constkeyCode = event.which || event.keyCode; if (keyCode === 190 && this.dotFlag) { this.dotFlag = true; event.returnValue = false; return; } else if (keyCode === 190) { this.dotFlag = true; } const specialkey = [8, 37, 39, 190].some((key) => key === keyCode); if ((keyCode >= 48 && keyCode <= 57 || specialkey)) { event.returnValue = true; } else { event.returnValue = false; } }
/*以下方式棄用,對中文輸入法無效*/
三、通過事件方式
1、html 程式碼:
<input type="text" (keydown)="onKeyPress($event)" >
2、angular2 函式48=<keyCode<=57為數字,字母或者其他同理,對中文輸入法無效(棄用)
onKeyPress(event:any){
const keyCode = event.which || event.keyCode; const specialkey = [8, 37, 39, 190].some((key) => key === keyCode); if ((keyCode >= 48 && keyCode <= 57 || specialkey)) { event.returnValue = true; } else { event.returnValue = false; }}