Javascript 如何在angular 4中进行onkeypress
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46939808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do onkeypress in angular 4
提问by Whitecat
I am trying to implement a input tag that only allows numbers to be put in.
我正在尝试实现一个只允许输入数字的输入标签。
One way that I found work is the following
我找到工作的一种方式如下
<input name="num"
type="number"
pattern="[0-9]*"
placeholder="Enter new PIN"
onkeypress="return event.charCode >= 48 && event.charCode <= 57"
title="Numbers only">
But I would like to change onkeypressfor an angular function. Is there anything that can work similar?
但我想换onkeypress一个角度函数。有什么可以类似的工作吗?
I have tried (keyup), and (change)but neither work the same. They allow the key to be pressed then remove the number.
我试过(keyup),(change)但两者的工作方式都不一样。他们允许按下键然后删除数字。
<input (keyup)="checkPin($event)"
type="number"
pattern="[0-9]*"
placeholder="Enter new PIN"
inputmode="numeric"
style="-webkit-text-security: disc;"></input>
Here is the TS function checkPin
这是TS函数 checkPin
checkPin($event: KeyboardEvent) {
console.log($event)
let value = (<HTMLInputElement>event.target).value;
if ($event.target) {
if (value == "") {
value = value.slice(0, 0);
}
if (value.length > 4) {
value = value.slice(0, 4)
}
(<HTMLInputElement>event.target).value = value.replace(/\D/g, '');
}
}
回答by Alan Grosz
TS method:
TS方法:
keyPress(event: KeyboardEvent) {
const pattern = /[0-9]/;
const inputChar = String.fromCharCode(event).charCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
event.preventDefault();
}
}
HTML:
HTML:
<input (keypress)="keyPress($event)"
type="number"
pattern="[0-9]*"
placeholder="Enter new PIN"
inputmode="numeric"
style="-webkit-text-security: disc;"></input>
Here the pattern in html is not needed because you are restricted to type another character than 0-9.
这里不需要 html 中的模式,因为您只能输入 0-9 以外的其他字符。
Good luck!
祝你好运!
回答by Tarun Majumder
We should use KeyboardEventinstead of event as a type of the input parameter of keyPress
我们应该使用KeyboardEvent代替事件作为输入参数的类型keyPress
回答by FiringBlanks
For anyone else looking for another way of determining if a specific key is pressed (like the space key), you can use:
对于正在寻找另一种方法来确定是否按下特定键(如空格键)的其他人,您可以使用:
grabText(event){
if(event.code === 'Space'){
console.log('PRESSED SPACE');
...
}
}

