我正在尝试在用户按下逗号(,)时清除输入。所以我要做的是,在(keypress)
上检查keyCode
,如果它是逗号,则可以通过将输入值设置为input.value = ''
来清除输入。
问题是,即使清除了我键入的字母,也不会清除逗号。我在做什么错了?
这是问题的fiddle。
步骤:
abc
。,
abc
已清除,但输入中仍然有,
。HTML:
<input type="text" #elem (keypress)="clearInput($event)">
代码:
@ViewChild( 'elem' ) public element;
clearInput( e: KeyboardEvent ) {
if ( e.keyCode === 44 ) {
this.element.nativeElement.value = '';
} else {
console.log('Not a comma');
}
}
我正在使用Angular 6。
答案 0 :(得分:11)
添加 preventDefault 。
在您的preventDefault()
代码中添加clearInput
,如下所示:
clearInput(e: KeyboardEvent) {
if (e.keyCode === 44) {
e.preventDefault(); // <-- Here
this.element.nativeElement.value = '';
} else {
console.log('Not a comma');
}
}
详细了解 preventDefault here。
答案 1 :(得分:7)
如果按下逗号,只需return false
:
class HomeComponent {
@ViewChild('elem') public element;
clearInput(e: KeyboardEvent) {
if (e.keyCode === 44) {
this.element.nativeElement.value = '';
return false;
} else {
console.log('Not a comma');
}
}
}
答案 2 :(得分:0)