我使用的是具有反应形式的角质材料,其中我有一个输入字段的类型数。我想将用户可以在文本框中输入的值从1限制到99。我能够做到这一点,但在键打开之后,我只看到了一小部分的值,然后在keyup事件中编写了切片逻辑之后,对值进行了切片。我试着用按键来写这个逻辑,但它似乎行不通。我尝试使用event.stopPropogation()和preventDefault,但没有成功。以下是代码:
<input type="number"
matInput
min="1"
max="99"
#tempVar
autocomplete="off"
formControlName="noOfWeeks"
(keyup)="imposeMinMax(tempVar)"
(keypress)="numericOnly($event)"
/>TS文件
numericOnly(e): boolean {
return e.keyCode === 8 && e.keyCode === 46
? true
: !isNaN(Number(e.key));
}
imposeMinMax(el) {
if (
el.value != '' &&
(parseInt(el.value) < parseInt(el.min) ||
parseInt(el.value) > parseInt(el.max))
) {
el.value = el.value.toString().slice(0, 2);
}
}发布于 2020-11-24 07:59:54
我可以建议一种使用keydown事件的方法:
<input type="number"
matInput
min="1"
max="99"
#tempVar
autocomplete="off"
formControlName="noOfWeeks"
(keydown)="handleKeydown($event)"
/>handleKeyDown(e) {
const typedValue = e.keyCode;
if (typedValue < 48 && typedValue > 57) {
// If the value is not a number, we skip the min/max comparison
return;
}
const typedNumber = parseInt(e.key);
const min = parseInt(e.target.min);
const max = parseInt(e.target.max);
const currentVal = parseInt(e.target.value) || '';
const newVal = parseInt(typedNumber.toString() + currentVal.toString());
if (newVal < min || newVal > max) {
e.preventDefault();
e.stopPropagation();
}
}当然,这个handleKeyDown方法可以进一步扩展,这取决于您的需求。
https://stackoverflow.com/questions/64981827
复制相似问题